The way to make an array using function_h​undle(関数ハン​ドルを用いた配列の作​り方)

関数ハンドルを用いた配列の作り方をご教授願いたいです。
例えば、
for i=1:5, f[i]=i.*x
としたときに
f[1]=x, f[2]=2.*x, f[3]=3.*x, f[4]=4.*x, f[5]=5.*x
といったデータが格納されるようなプログラムは可能しょうか?
ぜひよろしくお願いします。
I want the way to make an array using function_hundle.
For example, when I define
for i=1:5, f[i]=i.*x,
I wish to be stored
f[1]=x, f[2]=2.*x, f[3]=3.*x, f[4]=4.*x, f[5]=5.*x.
Please tell me the way...
Thank you.

댓글 수: 2

Is x an array or a single number?
vec=1:5
if it is a single number, then
f=vec.*x
if x is an array, then
f=x(:)*vec.' (assuming vec is a column vector)
Each column of vec will be x multiplied by the corresponding number.
Hope this helps.
Thank you for your support.
x is a variable.
So, I want to get 5 function_fundles.
Could you give me any ideas?
I'm sorry for that I'm poor in English and Matlab...
Thank you.

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

 채택된 답변

Walter Roberson
Walter Roberson 2020년 11월 30일
N = 5;
f = cell(N,1);
for i = 1 : N
f{i} = @(x) i.*x;
end
You cannot use () indexing to store different function handles; you have to use {} indexing.

댓글 수: 3

Yoshiki Sato
Yoshiki Sato 2020년 11월 30일
편집: Yoshiki Sato 2020년 11월 30일
>> N = 5;
f = cell(N,1);
for i = 1 : N
f{i} = @(x) i.*x;
end
>>
>> f{1}
ans =
値をもつ function_handle:
@(x)i.*x
>> f{2}
ans =
値をもつ function_handle:
@(x)i.*x
Thank you for your support.
On your way, I think all f{i} stores same function_hundle(@(x)i.*x).
I wish f{1} stores @(x)1.*x, f{2} stores @(x)2.*x...
Could you give me any ideas?
I'm sorry for that I'm poor in English and Matlab...
Thank you.
Try using them. They are not the same.
That was solved. Thank you so much!!

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

추가 답변 (1개)

KALYAN ACHARJYA
KALYAN ACHARJYA 2020년 11월 30일
편집: KALYAN ACHARJYA 2020년 11월 30일
Option 1:
i=1:5;
x=2;
f=i*x
Here resultant f array itself represents the f(1), f(2)..respectively depends on array length of i. Considering x is scalar.
Result:
f =
2 4 6 8 10
Option 2:
Please note function handle is different
i=1:5;
fun=@(x) i*x;
fun(2)
here created function handle with x as inputs. Once you pass the input as defined, it gives the resultant value
fun(2)
%...^ x value
You can create the function handle with both as inputs also
fun=@(i,x) i*x;
Result:
ans =
2 4 6 8 10
Option 3:
Create MATLAB custom function, save in the same working directory as fun1.m
function f=fun1(i,x)
f=i*x;
end
Now pass the input arguments from another matlab scripts or from command window
f=fun1(1:5,2)
Result:
>> f=fun1(1:5,2)
f =
2 4 6 8 10
Hope it helps! Keep Learning!

댓글 수: 1

Thank you for your support.
I wish to get 5 function_fundles like a Mr. Walter's way...
Could you give me any ideas?
I'm sorry for that I'm poor in English and Matlab...
Thank you.

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

카테고리

도움말 센터File Exchange에서 Matrix Indexing에 대해 자세히 알아보기

질문:

2020년 11월 30일

댓글:

2020년 12월 1일

Community Treasure Hunt

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

Start Hunting!

Translated by