matlab matrix question

Started by
6 comments, last by Brother Bob 17 years, 8 months ago
Hi, I need to use matlab for work, and Im getting into the matrix syntax... How would you go, without using 'for' loops, to create a square matrix of arbitrary size that looks like that: -2 -1 0 1 2 -2 -1 0 1 2 -2 -1 0 1 2 That is, the center column is all 0, and that decrease in steps of 1 to the left, in increase to the right... Any help? Thanks!
Advertisement
a = [-2 -1 0 1 2;     -2 -1 0 1 2;     -2 -1 0 1 2]; % Note, that's not square% Maybe more of what you want:first = -2;step = 1; last = 2;b = [first:step:last;     first:step:last;     first:step:last];% orfirst = -2;step = 1;last = 2;rows = 3;c = ones(rows,1)*[first:step:last];% or if you really always want it squarefirst = -2;step = 1;last = 2;d = ones(length([first:step:last]),1)*[first:step:last];% Edit:% Can omit the step if it's always = 1 (i.e first:last assumes a step of 1)

Tadd- WarbleWare
a=meshgrid(-first:last, ones(rows, 1));

Skip the last parameter if the matrix should be square, and a second matrix can be returned whose columns (the second parameter) are repeated instead of the rows.
Thanks guys!

The matrix will be square (not that it is a requirement, they just happen to be), I just got lazy typing the rows...

reana1's first example is not applicable (number of rows is too great, and may vary), but I'll try the others.
I have another question... how, in matrix notation, do I use matrix elements as indices in another matrix?

Kinda like using a lookup table

Something like

for i = 1..n
for j = 1..n
B(i,j) = N(A(i,j))
end
end

where A and B have the same size, and N is a vector. Is is possible to do this without using for loops?

Thanks again,

Use the matrix itself as index.
B = N(A);
Thats what I tried at first without success,
then I learned I need to initialise the size of the destination matrix beforehand. thanks :)
You don't have to initialize any destination matrices.

This topic is closed to new replies.

Advertisement