How to use a vector as an input in a function?

57 次查看(过去 30 天)
I have made this function:
function [AR,DEC] = astrometry(x,y,A,B,C,D,E,F)
AR = A*x+B*y+C;
DEC = D*x+E*y+F;
end
And I want to use some vectors as input:
input=[1,2,3,4,5,6,7,8]
But using:
[AR,DEC]=astrometry(input)
Gives me the following error:
Not enough input arguments.
Error in astrometry (line 2)
AR = A*x+B*y+C;
  1 个评论
Matt
Matt 2022-10-21
The function astrometry is expecting 8 inputs ( x,y ,a,b,... e,f) and you only give one input : a vector of size 1x8.
You can etheir write
[AR,DEC]=astrometry(input(1),input(2),input(3),...,input(8));
or define the function differently :
function [AR,DEC] = astrometry(input)
AR = input(1)*input(3)+ ...
DEC = ...
end

请先登录,再进行评论。

采纳的回答

dpb
dpb 2022-10-21
移动:dpb 2022-10-22
Carrying on from @Matt's comment above...
Is it really going to be more convenient to assemble all the elements into one long vector at the calling level? That's where/how to make the design decision on which is the better/best calling syntax.
function [AR,DEC] = astrometry(x,y,A,B,C,D,E,F)
AR = A*x+B*y+C;
DEC = D*x+E*y+F;
end
is convenient to write the function succinctly, but burdens the caller with all eight arguments every time. The 8-vector interface code would look something like Matt's start or...
function [AR,DEC] = astrometry(arg)
x=arg(1); y=arg(2);
A=arg(3);B=arg(4);C=arg(5);
D=arg(6);E=arg(7);F=arg(8);
AR = A*x+B*y+C;
DEC = D*x+E*y+F;
end
There are many variations on a theme, of course, besides...
function [AR,DEC] = astrometry(x,y,C1,C2)
A=C1(1);B=C1(2);C=C1(3);
AR = A*x+B*y+C;
DEC = C2(1)*x+C2(2)*y+C2(3);
end
which would package the two sets of coefficients as vectors. Of course, they could also be
function [AR,DEC] = astrometry(x,y,C1,C2)
AR = C1.A*x+C1.B*y+C1.C;
DEC = C2.A*x+C2.B*y+C2.C;
end
that puts the coefficients into two struct variables, each with consistent coefficient names by term, just different struct. That could then be an array of two as C(1).A, C(2).A, ... etc., or a single struct C.A where the field for each is a 2-vector and used as C.A(1) for first and C.A(2) for second.
The choices are all up to you, but your use then will have to be consistent to whatever choice you make.

更多回答(1 个)

Walter Roberson
Walter Roberson 2022-10-21
inputcell = num2cell(input) ;
[AR,DEC] = astrometry(inputcell{:});

类别

Help CenterFile Exchange 中查找有关 Programming 的更多信息

产品


版本

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by