matlab matrix question

This topic is 4226 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

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!

Share on other sites
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)

Share on other sites
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.

Share on other sites
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.

Share on other sites
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,

Share on other sites
Use the matrix itself as index.
B = N(A);

Share on other sites
Thats what I tried at first without success,
then I learned I need to initialise the size of the destination matrix beforehand. thanks :)

Share on other sites
You don't have to initialize any destination matrices.