How to update matrix values using algorithm based on position?

1 Ansicht (letzte 30 Tage)
Clark
Clark am 22 Sep. 2012
Suppose I've already create a square matrix, A=zeros(n).
Now let's say, for every position, A(i,j), I want to update the value to 1 / (i + j^2), can I do this easily?
Thanks!

Akzeptierte Antwort

Matt Fig
Matt Fig am 22 Sep. 2012
Bearbeitet: Matt Fig am 22 Sep. 2012
The straightforward way is to just use a loop:
A = zeros(n);
for ii = 1:n
for jj = 1:n
A(ii,jj) = 1/(ii+jj^2);
end
end
Here is another way to do it:
B = bsxfun(@(x,y) 1./(x+y.^2),(1:n).',1:n)

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by