Rick T
Rick T

Reputation: 3389

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.

Upvotes: 1

Views: 66

Answers (1)

Sardar Usama
Sardar Usama

Reputation: 19689

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)(:)];

Upvotes: 3

Related Questions