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!