Peterstone
Peterstone

Reputation: 7449

How to generate a matrix through a loop?

I´m wondering how to get these in Matlab:

a = 
1 3
2 4
3 5
4 6
5 7
6 8
7 9
8 10
9 11
10 12

Really the structure I want to do has 2 thousand files. but I will start with something easier. So I was thinking about to do it throught a loop:

for i=1:1:10
a(i) = [i i+2]
end

but this give an error:

???  In an assignment  A(I) = B, the number of elements in B and
I must be the same.

The idea is to generate a entire matrix (or structure, I suppose both are the same...) using a for loop (or may be there is a way to do it without any case of loop...). Does anyone could tell me how to do it? Thank you so much!

Upvotes: 0

Views: 28543

Answers (2)

samionb
samionb

Reputation: 1

The specific matrix, w/o loops, where n is no. of rows:

n=10;
a=(1:n)';
m=[a  a+2];

Upvotes: 0

Jonas Heidelberg
Jonas Heidelberg

Reputation: 5024

In your for loop, you are assigning two numbers to one element of your array a. Try

for i=1:1:10
  a(i,:) = [i i+2];
end

instead. Or, just use

a=[(1:10)' (3:12)'];

which replaces your loop...

Upvotes: 3

Related Questions