Reputation:
In matlab, how could you create a matrix M
using its indices to populate the values? For example, say I want to create a 3x3
matrix M
such that
M(i,j) = i+j --> [ 2 3 4; 3 4 5; 4 5 6]
I tried making vectors: x = 1:3'
, y = 1:3
and then
M = x(:) + y(:)
but it didn't work as expected.
Any thoughts on how this can be done?
Thanks!
UPDATE
The M
I actually desire is:
M(i,j) = -2^(-i - j).
Upvotes: 3
Views: 272
Reputation: 9864
You should use bsxfun
to find the sum:
M=bsxfun(@plus, (1:3).', 1:3)
and for the second formula:
M=-2.^(-bsxfun(@plus, (1:3).', 1:3))
Upvotes: 2
Reputation: 36710
bsxfun(@(x,y)(-2.^(-x-y)), (1:3).', 1:3)
This uses the Answer of Mohsen Nosratinia with the function you wished.
Upvotes: 1
Reputation: 11703
One way would be
x = 1:3;
z = ones(1,3);
N = z'*x + x'*z
M = -2 .^ -(z'*x + x'*z)
% Or simply
% M = -2 .^ -N
Output:
N =
2 3 4
3 4 5
4 5 6
M =
-0.250000 -0.125000 -0.062500
-0.125000 -0.062500 -0.031250
-0.062500 -0.031250 -0.015625
Upvotes: 1