array of function handle

조회 수: 9 (최근 30일)
Simo
Simo 2020년 6월 12일
댓글: Walter Roberson 2020년 6월 13일
I have to convert a code written using syms, to a code with function handle. (my prof doesn't want me to use syms)
how can I select the element of the array?
I write a simpler code
A=@(x)[sin(x), cos(x);1, -1];
B=@(x)[sin(x);cos(x)];
C=@(x) A(x)*B(x); % this is an array of 2 element
D=@(x) C(first element) - C(second element)

채택된 답변

Walter Roberson
Walter Roberson 2020년 6월 12일
First = @(x) x(1);
Second = @(x) x(2);
D = @(x) First(C(x)) - Second(C(x));
However, this will execute C twice. More efficient would be
FirstMinusSecond = @(x) x(1) - x(2);
D = @(x) FirstMinusSecond(C(x))
  댓글 수: 2
Simo
Simo 2020년 6월 13일
ok it works thanks, but if I want to plot D?
---------------------
l=linspace(0,3*pi);
plot(l,D(l))
--------------------
error:
--------------------
Error using vertcat
Dimensions of arrays being concatenated are not consistent.
Error in Untitled3 (line 3)
A=@(x)[sin(x), cos(x);1, -1];
Error in Untitled3 (line 5)
C=@(x) A(x)*B(x); % this is an array of 2 element
Error in Untitled3 (line 7)
D = @(x) FirstMinusSecond(C(x));
Error in Untitled3 (line 10)
plot(l,D(l))
Walter Roberson
Walter Roberson 2020년 6월 13일
Your A and B and C are only valid if x is a scalar, and your D would be unlikely to return the value you want if x is not a scalar. If you want to plot then instead of
plot(l,D(l))
do
y = arrayfun(D, l);
plot(l, y)

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Operators and Elementary Operations에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by