The way to make an array using function_hundle(関数ハンドルを用いた配列の作り方)
1 回表示 (過去 30 日間)
古いコメントを表示
関数ハンドルを用いた配列の作り方をご教授願いたいです。
例えば、
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 件のコメント
sushanth govinahallisathyanarayana
2020 年 11 月 30 日
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.
採用された回答
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 件のコメント
その他の回答 (1 件)
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!
参考
カテゴリ
Help Center および File Exchange で Matrix Indexing についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!