2
votes

I saw this other question but he's operating only on one index. I need to operate on both column and row indices without using a for loop. Is there a way to do this:

Let M (a,b) be the matrix and the size be the one in the parentheses. I want to manipulate each element as exp( (m-n)^2)

2
Yes, there are very many ways. But without you being more explicit about what you want to do and showing your prototype code, the closest to an answer you'll get is the first sentence in this comment.High Performance Mark
Alright. Let M (a,b) be the matrix and the size be the one in the parentheses. I want to manipulate each element as exp( (m-n)^2).sprajagopal
Behold -- as soon as you clarified your requirements useful answers appeared !High Performance Mark

2 Answers

7
votes

use bsxfun

M = exp( bsxfun( @minus, (1:a)', 1:b ).^2 );
3
votes

An alternative to using bsxfun, here, would be using meshgrid:

>> a = 5; b = 4; % Some example dimensions
>> [n, m] = meshgrid(1:b, 1:a)

n =

     1     2     3     4
     1     2     3     4
     1     2     3     4
     1     2     3     4
     1     2     3     4


m =

     1     1     1     1
     2     2     2     2
     3     3     3     3
     4     4     4     4
     5     5     5     5

>> M = exp((m - n).^2);

Note that this example is mainly instructive rather than practical - the bsxfun solution is faster and consumes less memory - but this shows how you could generate matrices of matrix subscripts.