how to use an array as the input variable for function
394 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
W. Feng
am 20 Jul. 2022
Bearbeitet: Stephen23
am 20 Jul. 2022
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
0 Kommentare
Akzeptierte Antwort
Chunru
am 20 Jul. 2022
% 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)
[d, e, f] = myfunc([6 7 3])
%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
0 Kommentare
Weitere Antworten (2)
Stephen23
am 20 Jul. 2022
Bearbeitet: Stephen23
am 20 Jul. 2022
You can use a comma-separated list:
For example:
Input_data = [1,2,3,4];
C = num2cell(Input_data);
[A,B,C] = myfunc(C{:})
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.
0 Kommentare
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!