Pass a structure to a function...
조회 수: 51 (최근 30일)
이전 댓글 표시
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...
댓글 수: 0
채택된 답변
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.
댓글 수: 0
추가 답변 (1개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!