1

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.

3
  • Please provide a sample output to make clear what you are after. What is i=j=n in your equation? Commented Oct 30, 2013 at 23:02
  • I think the poster means i=j=1...n. Commented Oct 31, 2013 at 0:23
  • Or rather i,j = 1...n Commented Oct 31, 2013 at 11:17

2 Answers 2

4

You can do it easily with bsxfun:

A = bsxfun(@power, 1:n, (1:n).');
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks!by the way, what's the meaning of (1:n).' ?
@Joey Cheng - See help punct for an interesting description of the punctuation operators in MATLAB. This is the non-conjugate transpose.
@JoeyCheng It is a column vector from 1 to n. You should read help punct as @chappjc says, it is very useful
2

Is this what you are after?

[A,b]=meshgrid(1:n);
M=A.^b;

5 Comments

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!
@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.
@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.
Thanks so much David, but can you briefly explain what is the meaning of meshgrid(1:n) and A.^b?
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.