Question

I have following simple program, but I want to extent it to a larger size. How I can do it much easier in Matlab: here the size of x is 6 but in my real program it has size 500.

x=[1 2 4 7 8 9];
y1=x(1);
y2=x(1)+x(2);
y3=x(1)+x(2)+x(3);
y4=x(1)+x(2)+x(3)+x(4);
y5=x(1)+x(2)+x(3)+x(4)+x(5);
y6=x(1)+x(2)+x(3)+x(4)+x(5)+x(6);
m=[y1 y2 y3 y4 y5 y6];
plot(x,m)

Thank you very much

Was it helpful?

Solution

plot(x,cumsum(x));

cumsum does exactly what you are looking for.

OTHER TIPS

For the first n elements of x you can do:

for i=1:n
y(i) = sum(x(1:i));
end
plot(x,y)

You can create array of (zeros) y's each of which has an index number.so you may use this index numbers in for loop. for example:

function O=Y(i)
num=0;
for m=1:i
num=num+x(i);
end
O=num;

you may use something similar to this.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top