I want to generate a n*n matrix in MATLAB, where each entry is A(i,j) = j^i, i=j=1...n but without using a for loop. In the MATLAB help, I saw a function matrix(m,n,f), but I don't know how to use that one.
2 Answers
You can do it easily with bsxfun:
A = bsxfun(@power, 1:n, (1:n).');
3 Comments
Joey
Thanks!by the way, what's the meaning of (1:n).' ?
chappjc
@Joey Cheng - See
help punct for an interesting description of the punctuation operators in MATLAB. This is the non-conjugate transpose.Luis Mendo
@JoeyCheng It is a column vector from 1 to n. You should read
help punct as @chappjc says, it is very usefulIs this what you are after?
[A,b]=meshgrid(1:n);
M=A.^b;
5 Comments
Joey
not exactly, I want every entry Aij to be j^i, so if n = 3, I will get [1,2,3;1,4,9;1,8,27], and can you explain the mechanisms behind the equation, by which I mean the meaning of the (1:n) the ' and the * means? Thanks a lot!
nispio
@JoeyCheng Please edit your question to include this information, instead of placing it in the comments. You can do this by clicking the "edit" button under your post.
David
@nispio I think his question is alright (apart from the i=j=n part). I had initially misread it as each element being i*j not i^j. It was my mistake.
Joey
Thanks so much David, but can you briefly explain what is the meaning of meshgrid(1:n) and A.^b?
David
Sure. Meshgrid link takes two vectors and constructs two matrices which give all the combinations of the input vectors. In this case, the input vector is
1:n which is the vector [1 2 3 4 5 ... n]. So you get two matrices like [1 1 1;2 2 2;3 3 3] and [1 2 3;1 2 3;1 2 3]. Then the A.^b is taking each element of A and raising it to the power of the corresponding element in b link. Hope that helps.
i=j=nin your equation?i=j=1...n.i,j = 1...n