MATLAB Answers

Mariana
0

Multiple loop doesn´t work with right values

Asked by Mariana
on 18 Mar 2014
Latest activity Commented on by Mariana
on 19 Mar 2014
Hello, I can´t figure out myself what is wrong with following nested loops:
index = 0;
for i = 1 : 2 : givenValue
index = index + 1;
j = i + 1;
for k = 1 : givenValue/2
if sth_x(k) > sth_y(k)
step(k) = sth_y(k) / sth_x(k);
end
end
for id = 1 : givenValue/2
values_x{index} = mat(i, 1) : mat(j, 1);
values_y{index} = mat (i, 2) : step(id) : mat(j, 2);
end
In words, what I need is to generate two cell arrays (values_x and values_y) with one row and several columns, which contains all points (pixels - it is image analysis) between points (pixels) mat(i,1) and mat (j,1) with growing i and j. values_x are allways increased with 1, but values_y are supposed to be increased with step counted before. Problem I have is that cell array values_y is generated with step from the last iteration only. I need values_y{1,1} to be counted with step 1 and values_y{1,2} to be counted with step 2. Therefore values_x{1,1} and values_y{1,1} will be the same length.
I´m new to matlab and I know this might be simple. But I really don´t know what is wrong. I tried to change order of "for" and "if", tried to replace "id" with "k" but still nothing works.
Thank you for your advices very much.

  0 Comments

Sign in to comment.

1 Answer

Answer by Nitin
on 18 Mar 2014

You might need to initialize your cells first before saving to it.
a = cell(1, num);

  3 Comments

Nitin, thank you for your answer. Unfortunatelly pre-allocating my cell array doesn´t help. I don´t know much about these things but I assumed that pre-allocating increase speed if cycle goes many times. This is cycle ith maximally 6 repetitions. Actually the problem is still the same (even after pre-allocation) - there are two cells in array values_y and they both are counted with the "step" from last iteration. If I write it without cycle with proper numbers it works. When I write in cycle for FIRST column (of matrix mat) it works also. But it doesn´t work when I write it in cycle for second column :( I think there must be some problem of indexing but still can´t figure out what it is :(
Hopefully this will help, I am not sure what you are trying to achieve though:
index = 0;
givenValue = 10;
step = 1:5;
values_x = cell(1,10);
values_y = cell(1,10);
mat= randi(20,20,2);
for i = 1 : 2 : givenValue
index = index + 1;
j = i + 1;
for k = 1 : givenValue/2
if 2 > 1
display('So far so good')
end
for id = 1 : givenValue/2
values_x{index} = mat(i, 1) : mat(j, 1);
values_y{index} = mat (i, 2) : step(id) : mat(j, 2);
end
end
end
For example you can access the elements in the array using values_x{1}
Thanks for your try :) I copied code into my editor and tried to run it, but it didn´t make me understand how I could solve my problem :( Probably I can ´t explain my problem well via text online. But once again thank you

Sign in to comment.