MATLAB: Writing calculation results into matrix

MATLABmatrix manipulation

Hi,
I am trying to write results into each matrix row c = zeros(4, length(a)). I have set of steps x = [1,2,3,4]. After the 1st five values for each step are calculated I want to write them into 4 rows of a single matrix. So, eventually it should be something like
c = ( 2 6 9 4 8 9 4 9 5 8
9 4 6 9 5 9 0 0 0 0
4 9 7 3 5 0 0 0 0 0
7 8 5 7 0 0 0 0 0 0)
I want then slice this matrix and make a single line plot which is also a question because I didn't try to do it so far. Therefore, any advises are very welcome. Thanks!
x = [1,2,3,4];
flag = 0;
for s = 1:length(x)
a = (1:x(s):50);
p = zeros(1,length(a));
c = zeros(4,length(a));
for i = 1:length(a)
p(i) = 3.*a(i) + 2;
v(i) = 4.*a(i) + 2;
if i == 5
c(1,:)=p
flag = 1;
break
end
end
if flag == 1
continue
end
end

Best Answer

When I ran your code, this is the output that it gives:
res =
5 8 11 14 17
5 11 17 23 29
5 14 23 32 41
5 17 29 41 53
With some minor changes to your code I also managed to get c to be the same matrix too. But rather than fixing that buggy code, here is a much neater and faster way to do it:
>> s = 4;
>> n = 5;
>> x = 1:s;
>> Y = cumsum([ones(s,1),repmat(x(:),1,n-1)],2);
>> Z = 3*Y + 2
Z =
5 8 11 14 17
5 11 17 23 29
5 14 23 32 41
5 17 29 41 53
The documentation will tell you how cumsum and repmat work. If you plan on using MATLAB you should learn about vectorization, lets you write faster, neater and easier code in MATLAB, without using loops.