Borrar filtros
Borrar filtros

Pass a structure to a function...

51 visualizaciones (últimos 30 días)
Raviteja
Raviteja el 4 de Feb. de 2011
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...

Respuesta aceptada

Andrew Newell
Andrew Newell el 4 de Feb. de 2011
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.

Más respuestas (1)

Raviteja
Raviteja el 4 de Feb. de 2011
Dear Andrew,
Thank you very very much! Iam struggling from 2 days!
Your guidance helped me a lot!

Categorías

Más información sobre Logical en Help Center y File Exchange.

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by