Making a FOR loop more efficient in Octave

主宰稳场 提交于 2020-03-25 18:05:37

问题


I have a working FOR loop below and was wondering if there was a way to get rid of the if / then / else statement?

c = randi([-10 10],1,4); %create random integers
[rw col]= size(c); %get size of array

num_of_loops=5 %number of loops to iterate
a= zeros(num_of_loops,col); %allocate memory to array
b= zeros(1,(rw*col)); %allocate memory to array

a(1,:)=c; %add c array to 1st row in array 

for n=1:num_of_loops
  n
  if (n==1)
    last_num_in_array=c(1,end); %get last number in array
    a(2,:)=last_num_in_array+c; %start with the last number from row above in array and add original c array to it
  else
    last_num_in_array=a(n-1,end); %get last number in array
    a(n,:)=last_num_in_array+c; %start with the last number from row above in array and add original c array to it
  endif

endfor

b=reshape(a',1,[]);

Here's some example random data. Note the data will be random data.

c= 
7   -2  -4  -8

a=
 7  -2  -4  -8
-1  -10 -12 -16
-9  -18 -20 -24
-17 -26 -28 -32
-25 -34 -36 -40

b=
7   -2  -4  -8  -1  -10 -12 -16 -9  -18 -20 -24 -17 -26 -28 -32 -25 -34 -36 -40                                                             

来源:https://stackoverflow.com/questions/60244381/making-a-for-loop-more-efficient-in-octave

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!