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

조회 수: 57 (최근 30일)
Inti
Inti 2022년 10월 21일
이동: dpb 2022년 10월 22일
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