简体   繁体   中英

vectorize FOR loop in octave

I'm trying to get rid of the FOR loop and vectorize this if possible. The numerical data in the variable data1 will not be sequential data / numbers but random numerical data.

ii=0;
data1=[1,2,3]; %test data will be random data this will not be sequential numbers 
array_joined=[];
for ii = 0:2
  ii+1;
  array_joined=[array_joined; data1(:),repmat(ii,[1,length(data1)])(:)]
endfor

Result:

1   0
2   0
3   0
1   1
2   1
3   1
1   2
2   2
3   2

I'm using Octave 4.4 which is similar to Matlab.

repmat can be used on both data1 and iteration variable ii as follows:

data1 = [1,2,3];    ii = 0:2;  %inputs
array_joined = [repmat(data1.',numel(ii),1) repmat(ii,numel(data1),1)(:)];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM