开发者

running a function on each cell in a matrix, knowing the index a cell, without using loops

开发者 https://www.devze.com 2023-03-31 22:36 出处:网络
I have a function F that receives an 2D index (i and j) and a constant array C. I want to run this function on each cell in a matrix, meaning - in the (i,j) cell I\'ll have the value F(i,j,C).

I have a function F that receives an 2D index (i and j) and a constant array C. I want to run this function on each cell in a matrix, meaning - in the (i,j) cell I'll have the value F(i,j,C).

Is there a way to do it in matlab without using loop开发者_高级运维s?


To apply a function to every item in an array or matrix, use arrayfun.

m = [1:3; 4:6];
arrayfun(@(x) x + 1, m)

To use arrayfun, you need to modify the signature of your function F so that it takes the item in your matrix at (i,j), not the indicies themselves.

Also, a purely vectorised solution is often faster than using arrayfun. For example, compare

tic; for(i = 1:1000); mean(m(:)); end; toc
tic; for(i = 1:1000); arrayfun(@mean, m); end; toc
0

精彩评论

暂无评论...
验证码 换一张
取 消