Evaluate an anonymous function for each value in a matrix

14 ビュー (過去 30 日間)
Payson
Payson 2023 年 5 月 4 日
回答済み: Dyuman Joshi 2023 年 5 月 4 日
I want to evaluate a function for every value in a matrix, but MATLAB thinks I want to input the entire matrix into the function.
f = @(x) x*sin(x);
a = [1 2 3;4 5 6];
f(a)
ERROR: "incorrect dimensions"
^this makes sense because it thinks i want a*sin(a) instead of a(i,j)*sin(a(i,j) for i = 1:3 and j = 1:2
In another implementation like multiplication I would use ".*" to signify elemtwise calculations so I am assuming there is something similar for anonymous functions.
I could use a loop for this example but I want to implement it in a more complicated application so I would be a much larger headache.

採用された回答

Dyuman Joshi
Dyuman Joshi 2023 年 5 月 4 日
"In another implementation like multiplication I would use ".*" to signify elementwise calculations so I am assuming there is something similar for anonymous functions."
Yes, use element-wise operations while defining the function handle
f = @(x) x.*sin(x);
a = [1 2 3;4 5 6];
f(a)
ans = 2×3
0.8415 1.8186 0.4234 -3.0272 -4.7946 -1.6765

その他の回答 (0 件)

カテゴリ

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

製品


リリース

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by