How to use a vector as an input in a function?
131 views (last 30 days)
Show older comments
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 Comment
Matt
on 21 Oct 2022
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
Accepted Answer
dpb
on 21 Oct 2022
Moved: dpb
on 22 Oct 2022
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.
0 Comments
More Answers (1)
Walter Roberson
on 21 Oct 2022
inputcell = num2cell(input) ;
[AR,DEC] = astrometry(inputcell{:});
0 Comments
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!