matlab matrix question
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!
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)
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.
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,
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,
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement