Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get index of current element of a 2-D matrix within arrayfun

Let M be some matrix:

M = rand(1000, 2000);

Consider the following code example:

A = zeros(size(M));
for row = 1:1000
    for col = 1:2000
        A(row, col) = M(row,col)*(row + col);
    end
end

How to compute the matrix A without for loops?

There is arrayfun function, but I don't know how get the index of the current element:

A = arrayfun(@(x)(x*(index(1) + index(2))), M); %// but how to get index???

Perhaps there are other solutions (and without extra loops)?


2 Answers

You can do something simple like as follows to get a matrix that will represent row+col and then multiply that by M

M = rand(1000, 2000);
rowPlusCol = bsxfun(@plus,(1:size(M,1)).',1:size(M,2));
A = M.*rowPlusCol;

From my experience bsxfun is an extremely powerful function and can definitely save some run time, and this is a perfect example of that.

like image 86
MZimmerman6 Avatar answered Jan 29 '26 11:01

MZimmerman6


Here's an alternative solution, boasting another fancy one-liner, for the sake of diversity:

A = M .* hankel(2:size(M, 1) + 1, size(M, 1) + 1:sum(size(M)));
like image 44
Eitan T Avatar answered Jan 29 '26 13:01

Eitan T



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!