How can I use a vector inside an @fun?

3 ビュー (過去 30 日間)
Carlos Zúñiga
Carlos Zúñiga 2019 年 10 月 22 日
コメント済み: Carlos Zúñiga 2020 年 8 月 31 日
Hello everyone,
I want to define a function like "fun = @(x) sin(a*x)" where "a" is a vector of n dimention.
Do you have any idea?
Thank you for your support.
Greetings.

採用された回答

Artemio Soto Breceda
Artemio Soto Breceda 2019 年 10 月 22 日
I might not be understanding your question properly, but it looks like your code works just fine. Here is an example:
a = linspace(0,2*pi,1000); % Create a vector of dimension N = 1000 with values increasing
% linearly from 0 to 2*pi
fun = @(x) sin(a*x); % Define your function
plot(a, fun(1)); % plot 1 period of the sine wave (from 0 to 2*pi);
hold
plot(a, fun(2)); % x = 2
plot(a, fun(4)); % x = 4
sinewave_example.png
I made a a 1000 elements vector, then used your exact code to define fun, and used the new function with three different inputs. Works perfectly as you wrote it.
  2 件のコメント
Walter Roberson
Walter Roberson 2019 年 10 月 23 日
I agree, in the context provided, using a vector or matrix inside an anonymous function is not a problem.
The kinds of problems that can arise:
  • the majority of the time you should use the vector operations such as .* and .^ and ./ instead of * and ^ and /
  • fzero and the minimizers such as fmincon cannot work with vectors or arrays being returned: gamultiobj is the only minimizer that can work with vectors being returned
  • integral() can only deal with vectors or arrays being returned if you use the 'arrayvalued' option
  • integral2() cannot deal with vectors or arrays being returned
  • if you are using arrayfun() or cellfun() or stuctfun() then you need to use 'uniform', 0 to return non-scalars
Carlos Zúñiga
Carlos Zúñiga 2020 年 8 月 31 日
Thank you!

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

その他の回答 (1 件)

Joe Vinciguerra
Joe Vinciguerra 2019 年 10 月 23 日
Assign 'a' first, then assign 'fun'. In your application I don't believe you can do it the other way around.
  1 件のコメント
Carlos Zúñiga
Carlos Zúñiga 2020 年 8 月 31 日
Thank you!

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

カテゴリ

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by