# Add values to a Matrix

3 views (last 30 days)
Antonio Jayena on 25 Mar 2015
Answered: Andrew Newell on 26 Mar 2015
Hello!
I have the following code:
p=0;
num=0:1:3;
cont=0;
i=0;
b=0;
n=0;
for k=1:num(end)
ss = [];
[fil,col]=size(s);
for i=1:fil
if ((s(i,2))< 0.5)&&(s(i+1,2)-(s(i,2))>2)&& p>0
cont=cont+1;
n=s(i, 1);
display(s(i, 1)-b);
p=p-1;
else if ((s(i,2))< 0.5)&&(s(i+1,2)-(s(i,2))>2)&& p==0
cont=cont+1;
display(s(i, 1)-n);
b=s(i, 1);
p=p+1;
else if (cont==25)
p=0;
num=0:1:3;
cont=0;
i=0;
b=0;
n=0;
break
end
end
end
end
end
And my intention is to, (in each iteration of any of both IF loops), save in a M matrix all the values that appears in the display (for all the iterations).
It is possible?
Thank you
##### 2 CommentsShowHide 1 older comment
Antonio Jayena on 25 Mar 2015
Thank you for your help Im new on Matlab. Yes you are right with the elseif problem.
I want to save all the values of all the iterations in a Matrix 1xn (of the IF's loops) of
(s(i, 1)-b)
and
(s(i, 1)-n)
In each iteration

Andrew Newell on 26 Mar 2015
If you're trying to collect all the values for the inner loop ( for i=1:fil ), you could try putting
M = [];
above the loop, and replacing
display(s(i, 1)-b);
by
M = [M s(i, 1) - b];
and
display(s(i, 1)-n);
by
M = [M s(i, 1)-n];
It's better if a vector of the correct size is preallocated before the loop starts, but I don't know how large M will be.