フィルターのクリア

fast way of filing up a matrix with function calls

1 回表示 (過去 30 日間)
Kaushik
Kaushik 2012 年 12 月 21 日
i have a 2-D matrix m(i,j). for each (i,j) some function f(i,j) has to be evaluated and that fills up the matrix m(i,j). presently i am using a loop for i=1:N for j=1:N mat(i,j) = f(i,j); to fill up the matrix. Is there a faster implementation of this piece of code.
  1 件のコメント
Matt J
Matt J 2012 年 12 月 21 日
What does f() look like?

サインインしてコメントする。

回答 (2 件)

Matt J
Matt J 2012 年 12 月 21 日
編集済み: Matt J 2012 年 12 月 21 日
If f() is element-wise vectorized, you could do this
[I,J]=ndgrid(1:N,1:N);
mat=f(I,J)
but more optimal approaches might still be possible depending on the form of f().

Azzi Abdelmalek
Azzi Abdelmalek 2012 年 12 月 21 日
編集済み: Azzi Abdelmalek 2012 年 12 月 21 日
M=rand(4); % your matrix
f=@(x) sin(x)*x % your function
out=arrayfun(@(x) f(x),M)
Or you can use operation element by elemment (Faster)
out=sin(M).*M
  4 件のコメント
Kaushik
Kaushik 2012 年 12 月 21 日
thank you for your answer. well my grid is something like x_grid (has length M) y_grid (has length N). and my output matrix will have size M*N. and output(i,j) = f(x_grid(i),y_grid(j),other parameters) inside f(x_i,y_i,other param) { i do integration of some kind on splines}. so you see the function has to take in two different values x,y in from two different vector and compute.
Azzi Abdelmalek
Azzi Abdelmalek 2012 年 12 月 21 日
編集済み: Azzi Abdelmalek 2012 年 12 月 21 日
x_grid=1:5;
y_grid=1:4;
[M1,M2]=meshgrid(x_grid,y_grid)
Then calculate using M1 and M2

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by