Evaluate function handle for each value in vectorized form

2 ビュー (過去 30 日間)
Salomon Roth
Salomon Roth 2021 年 6 月 1 日
回答済み: Jan 2021 年 6 月 2 日
I initialize a relatively simple function handle that depends on alpha. For simplicity, I will use alpha = 1.
For beta and gamma, I use n=10 random draws, where beta are scalars and gamma are 3 by 1 vectors.
I want to evaluate the function handle for each of the n random draws. This can be achieved e.g. by a for loop.
How can this be achieved in a more Matlab-like (vectorized) way?
Thanks.
alpha = 1;
n=10;
rng default
beta_all = randn(n, 1);
gamma_all = randn(3, n);
res = cell(n, 1);
for k=1:length(res)
beta = beta_all(k);
gamma = gamma_all(:,k);
y = @(alpha) (alpha * beta * gamma);
res{k} = y(alpha);
end
  4 件のコメント
Jan
Jan 2021 年 6 月 1 日
Maybe the problem gets more clear, if you post the real code, not a strongly simplificated version. If you need "alpha +- something", you could use:
res{k} = (alpha + x) * beta * gamma;
Salomon Roth
Salomon Roth 2021 年 6 月 2 日
Thanks Jan, you were right. Indeed, it is possible to proceed as you have outlined (alpha + x), i.e., the function handle is not necessary. However, I still wonder if the for loop is needed to evaluate the function for each of the n random draws?

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

採用された回答

Jan
Jan 2021 年 6 月 2 日
alpha = 1;
n=10;
rng default
beta_all = randn(n, 1);
gamma_all = randn(3, n);
res = num2cell(alpha * beta_all.' .* gamma_all, 1).';

その他の回答 (0 件)

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by