arrayfun syntax and use with scalar input

4 ビュー (過去 30 日間)
checker
checker 2020 年 5 月 28 日
コメント済み: checker 2020 年 5 月 28 日
Hello people,
I've been (ab)using arrayfun and cellfun for some time without fully understanding the syntax. It centers around '@' symbol followed by the arguements.
To demonstrate, if I want to add 2 arrays, I can do:
a=[1 2;3 4];
b=[5 6;7 8];
c=arrayfun(@(x,y) x+y,a,b);
But what if I wanted to simply add a scalar?
a=[1 2;3 4];
b=2;
c=arrayfun(@(x,y) x+y,a,b);
Error: All of the input arguments must be of the same size and shape.
Previous inputs had size 2 in dimension 1. Input #3 has size 1
So is there a good summary of arrayfun as it's used above? Can one treat an input as a scalar or vector and others as arrays?
Thanks,
-Chris
  2 件のコメント
Stephen23
Stephen23 2020 年 5 月 28 日
"Can one treat an input as a scalar or vector and others as arrays?"
No, but you can easily parameterize the function using an anonymous function:
checker
checker 2020 年 5 月 28 日
Thanks for the link. I'll spend some time on it.

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

採用された回答

James Tursa
James Tursa 2020 年 5 月 28 日
To use a scalar you could use this syntax:
a=[1 2;3 4];
b=2;
c=arrayfun(@(x)x+b,a);
The function handle would pick up b from the workspace.

その他の回答 (0 件)

カテゴリ

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