Rick T
Rick T

Reputation: 3389

Creating numbers with "For loop" using matlab / octave

I'm trying to loop a pattern of numbers using a For loop in matlab / octave The pattern I'm looking for is 40,80,160,320,280,200 and then 1 is added to each one so the pattern would look like this:

40,80,160,320,280,200,41,81,161,321,281,201,42,82,162,322,282,202

I tried using a for loop below

clear all
numL_tmp=[40;80;160;320;280;200]

numL=[numL_tmp];
for ii=1:length(numL_tmp)
    for jj=1:4
        numL=[numL;numL_tmp(ii,1)+jj]
    end
end

But I get

40,80,160,320,280,200,41,42,81,82,161,162,321,322,281,282,201,202

How can I fix this?

Upvotes: 0

Views: 225

Answers (3)

Roney Michael
Roney Michael

Reputation: 3994

For the problem stated, nested loops are unnecessary. You could simply do the following:

clear all;
numL_tmp=[40;80;160;320;280;200];

numL = numL_tmp;
for ii=1:2
    numL = [numL;numL_tmp+ii];
end

numL

This would yield:

numL =

    40
    80
   160
   320
   280
   200
    41
    81
   161
   321
   281
   201
    42
    82
   162
   322
   282
   202

This works because MATLAB recognizes the piece of code numL_tmp+ii as something equivalent to numL_tmp + ii*ones(size(numL_tmp)).

Upvotes: 3

Stuart
Stuart

Reputation: 885

There are easier ways to do it, but the fundamental problem with your code is that the inner and outer loops in the wrong order. See what happens if you leave your code as is, but simply interchange the order of the two loops:

...
numL=[numL_tmp];
for jj=1:4
    for ii=1:length(numL_tmp)
       numL=[numL;numL_tmp(ii,1)+jj]
   end
end

Upvotes: 2

yuk
yuk

Reputation: 19870

You can avoid loops completely:

N = 3;
numL = kron(ones(N,1),numL_tmp) + kron((0:N-1)',ones(numel(numL_tmp),1));

Upvotes: 3

Related Questions