1 view (last 30 days)

Show older comments

Hello,

I am trying to check if parts of different sizes of a vector are equal to ones' vector of the part's size. Let me be more clear on what I mean:

Suppose that we are given a matrix like the following:

a = [0 0 0 0 1;

0 1 0 0 0;

0 0 0 1 0;

0 0 1 0 0;

1 0 0 0 0]

and also a vector with elements whose sum is equal to the number of the columns in the a matrix. For example:

b =[3 2];

As you can see 3+2 = 5, where 5 is the number of columns in the a matrix.

Now, we are summing the rows of the a matrix dynamically in a loop, and we store this sum in a vector called c. In the example I am using c would be like that in the loop:

first iteration:

c = [0 1 0 0 1]

second iteration:

c = [0 1 0 1 1];

third iteration:

c = [0 1 1 1 1];

fourth iteration:

c = [1 1 1 1 1];

For each iteration what I want to do is to check the following in the example I am using:

I want to check if c from 1 to 3 is equal to ones(1,3) and if c from 4 to 5 is equal to ones(1,2).

I want this check to be done dynamically in the loop and print something when this happens.

I have written a following sample of code which works for some examples I have used:

ni = 5;

noperations = [3 2];

sumoperations = [0 0 0 0 1;0 1 0 0 0;0 0 0 1 0;0 0 1 0 0;1 0 0 0 0]

k=2;

oper = zeros(1,ni);

i=1;

paraggelies = zeros(1,length(noperations));

index = 1;

while (k<=ni)

sumoperations(k,:) = sumoperations(k-1,:) + sumoperations(k,:);

oper(1,:) = sumoperations(k,:)

for i=1:length(noperations)

if(i == 1)

if(oper(1:noperations(i)) == ones(1,noperations(i)))

% disp('Finished Order number')

% disp(i)

paraggelies(index) = i;

index = index+1;

end

else

if(oper(noperations(i-1)+1:noperations(i-1)+noperations(i)) == ones(1,noperations(i)))

% disp('Finished Order number')

% disp(i)

paraggelies(index) = i;

index = index+1;

end

end

end

k = k+1;

end

paraggeliesnew = [];

index = 1;

for i = 2:length(paraggelies)

if(paraggelies(i) ~= paraggelies(i-1))

paraggeliesnew(index) = paraggelies(i-1);

index = index+1;

end

end

but it is pretty slow for the purpose I want to use it and maybe it is buggy.

Is there another way (more vectorized/more "matlab") to achieve efficiency with speed of the problem I described you?

I would greatly appreciate your help.

Thank you for your answers and for your time in advance,

Chris

Image Analyst
on 6 Nov 2016

How about vectorizing c:

% Get sums of columns:

c = sum(sumoperations, 1);

Then check c :

indexes1 = 1:b(1);

indexes2 = (b(1)+1) : (b(1) + b(2));

if all(c(indexes1) == 1)

% Then do something.....

end

if all(c(indexes2) == 1)

% Then do something.....

end

I'm using all() to check that every one of the c elements is exactly 1. This can be extended to any number of elements in b of course -- just follow the pattern.

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!