how to use an array as the input variable for function

321 次查看(过去 30 天)
I would like to use an array as the input to call the main function. how to make it?
E.g
function [a b c]=myfunc( x1,x2,x3,x4, ...xn)
a=x1+x2;
b=a;
c=x1*x2*x3...xn;
end
Now I want to use below array as the input to call above function.
Input_data=[¨1 2 3 4 ....n]
feval(myfunc, [1 2 3 4 ... n]) then it's working. But I want to use an array Input to make it rather than list these values.
feval(myfunc, Input_data ) is not working becasue all the values assign to the first variable x1
help help

采纳的回答

Chunru
Chunru 2022-7-20
% Now I want to use below array as the input to call above function.
Input_data=[1 2 3 4 5];
%feval(myfunc, [1 2 3 4 ... n])
[a, b, c] =myfunc(Input_data)
a = 3
b = 3
c = 120
[d, e, f] = myfunc([6 7 3])
d = 13
e = 13
f = 126
%function [a b c]=myfunc( x1,x2,x3,x4, ...xn)
function [a, b, c]=myfunc( x ) % where x is an array
a=x(1)+x(2); % access array elements
b=a;
c=prod(x); % x1*x2*x3...xn;
end

更多回答(2 个)

W. Feng
W. Feng 2022-7-20
The function file name is M=myfunction.m. and there are 39 inputs.
[ ]=myfunction( a, b,c, ...)
the array X with 39 values as input X=¨[x1,x2,...x39] how to execute the function only use myfunction, and X.
could we do it only use M and X to make it
feval(M(1:end-2), X)
  2 个评论
W. Feng
W. Feng 2022-7-20
[M_function, path1, index1]=uigetfile('*.m')
%then select the main function myfunc.m as below m.file
function [y1,y2]=myfunc (x1, x2, x3, x4,x5,x6,x7)
y1=x1+x2+x3+x4+x5+x6+x7;
y2=y1*y1;
%M_function='myfunc.m', the input was stored with
%assume Input=[1,2,3,4,5,6,7] array Input is got from other file.
%How to calculate only with Input, and M_function
%if we use
feval(M_function(1:end-2),1, 2, 3,4, 5 ,6 ,7)
% the calculation is succssful, but I just want to use such synax to use aviable Input instead of using the real value.

请先登录,再进行评论。


Stephen23
Stephen23 2022-7-20
编辑:Stephen23 2022-7-20
You can use a comma-separated list:
For example:
Input_data = [1,2,3,4];
C = num2cell(Input_data);
[A,B,C] = myfunc(C{:})
A = 3
B = 3
C = 24
function [a b c]=myfunc( x1,x2,x3,x4)
a=x1+x2;
b=a;
c=x1*x2*x3*x4;
end
"The function file name is M=myfunction.m. and there are 39 inputs."
39 positional input arguments is excessive. Most likely you should rewrite the function to accept vector/array inputs, rather than lots and lots of separately-named input arguments. Most likely that would make your code simpler and more efficient, e.g. using PROD rather than repeatedly calling *, just as Chunru showed you.

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

产品

Community Treasure Hunt

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

Start Hunting!

Translated by