フィルターのクリア

Pass a structure to a function...

51 ビュー (過去 30 日間)
Raviteja
Raviteja 2011 年 2 月 4 日
Hello, I crated a structure
>> A(1).vect=[1 2 3 4]';
>> A(2).vect=[4 5 2 1]';
>> A(3).vect=[7 5 3 8]';
And I wrote a function to find average of vectors which are in this "A.vect" structure. And stored in a separate .m file with the same name avg_fun.m
%-------------------------------------
function [avg]=avg_fun(X,no_of_vect)
avg=0;
for i=1:no_of_vect
avg=avg+(X(1,i));
end
avg=avg/nofv;
%-------------------------------------
Then I tried my test:
>>avg_fun(A.vect,3)
Error showing:
Function definitions are not permitted at the prompt or
in scripts.
My doubt here is: How to pass a structure to a funtion ? What I have written in the funtion arguments
function [avg]=avg_fun(X,no_of_vect)
is correct ? (i.e writing X is correct ?)
Expecting right answer... And right code...

採用された回答

Andrew Newell
Andrew Newell 2011 年 2 月 4 日
You seem to have a number of problems here. First, you need to save the function to a separate file called avg_fun.m. Second, you need to pass the structure rather than its subfield because A.vect is interpreted as three inputs. Third, you are normalizing by the undefined variable nofv, which should be no_of_vect.
Here is the corrected function:
function [avg]=avg_fun(X,no_of_vect)
avg=0;
for i=1:no_of_vect
avg=avg+(X(1,i).vect);
end
avg=avg/no_of_vect;
and here is the script to call it:
A(1).vect=[1 2 3 4]';
A(2).vect=[4 5 2 1]';
A(3).vect=[7 5 3 8]';
avg_fun(A,3)
EDIT: You could also use a built-in function to do this:
mean([A.vect],2)
This collects the vectors into a matrix and sums across each row.

その他の回答 (1 件)

Raviteja
Raviteja 2011 年 2 月 4 日
Dear Andrew,
Thank you very very much! Iam struggling from 2 days!
Your guidance helped me a lot!
  1 件のコメント
Andrew Newell
Andrew Newell 2011 年 2 月 4 日
Glad to help.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by