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)?
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.
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)));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With