Jump to content
  • Advertisement
Sign in to follow this  
Steadtler

matlab matrix question

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

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
Share on other sites
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];

% or
first = -2;
step = 1;
last = 2;
rows = 3;
c = ones(rows,1)*[first:step:last];

% or if you really always want it square
first = -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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!