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

52 ビュー (過去 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 Center および File ExchangeProgramming についてさらに検索

製品


リリース

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by