필터 지우기
필터 지우기

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!

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by