How can I receive value in array by using function?

1 visualización (últimos 30 días)
Syed Ali Hassan
Syed Ali Hassan el 23 de Abr. de 2014
Comentada: Geoff Hayes el 23 de Abr. de 2014
function [P1n,P2n,P3n]=init_ffa(n,range)
% function [Pn{1:3}]=init_ffa(n,range)
%
% tempn=2;
% Prange = zeros(1, 3);
% Pn = zeros(1, 3);
% for k=1:3
% Prange{k}=range(tempn)-range(tempn-1);
% Pn{k}=rand(1,n)*Prange{k}+range(tempn-1);
% tempn= tempn + 2;
% end
P1range=range(2)-range(1);
P2range=range(4)-range(3);
P3range=range(6)-range(5);
P1n=rand(1,n)*P1range+range(1);
P2n=rand(1,n)*P2range+range(3);
P3n=rand(1,n)*P3range+range(5);
I want to replace P1n,P2n,P3n with simple array. like function [P1n,P2n,P3n]=init_ffa(n,range) replace with function [Pn{1:3}]=init_ffa(n,range) I try comment statements. But that isn't work.
  2 comentarios
Geoff Hayes
Geoff Hayes el 23 de Abr. de 2014
Hi Syed,
It isn't clear to me what you are asking. Are you trying to populate the output array value (Ligthn) or manipulate some other array?
Please edit your above question so that it is formatted as readable code. Use the {}Code button to do so.
Geoff
Geoff Hayes
Geoff Hayes el 23 de Abr. de 2014
In your above code, you are initializing Prange and Pn as vectors of zeros, and then accessing the kth element as if the vectors were vectors of cells. This will generate an error, so please replace Prange{k} with Prange(k) and Pn{k} with Pn(k).
Rather than returning three vectors, P1n, P2n, and P3n, why not just return a matrix with three rows:
function [Pn] = init_ffa(n,range)
% initialize Pn with 3 rows and n columns
Pn = zeros(3,n);
% initialize each row of Pn with a vector of random numbers and
% some product
Pn(1,:) = randn(1,n)*P1range+range(1);
Pn(2,:) = randn(1,n)*P2range+range(3);
Pn(3,:) = randn(1,n)*P3range+range(5);
(The colon : in the above code simply means all columns in row 1 or 2 or 3. If you just want the element in the first column of row one, it is Pn(1,1). If you want the first three elements of row one, the code is just Pn(1,1:3).)
Of course, you can now do something similar to what you have already tried in your for loop (which you have commented out). The trick is to just initialize your output as a matrix, and then on the ith iteration of the loop, set the ith row (your 1,2, or 3) to the data:
for k=1:3
% do something to get some range values
% set the ith row of output
Pn(i,:) = .;
end
In the above, Pn(i,:) just means set all column elements (use of the colon :) in row i to whatever.
Hope that this helps!
Geoff

Iniciar sesión para comentar.

Respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by