Variable

Hello, If i have
X=rand(20,1)
Y=rand(20,1)
then i want to do
p1=[x(1) y(1)]
p2=[x(2) y(2)]
. . .
. . .
. . .
p20=[x(20) y(20)]
How can i intialize these p1 to p20 values with the help of loop instead of intiallizing manually?
The varaible needs to be updates as p1...p20.
Finally with structure P has terms p1...p20, with p1...p20 have their values from X and Y
Thanks in advance

 Respuesta aceptada

Andrei Bobrov
Andrei Bobrov el 7 de Sept. de 2011

0 votos

variant use cell array
X=rand(20,1)
Y=rand(20,1)
p = mat2cell([X Y],ones(20,1),2)
bad version
for j1 = 1:size(X,1)
jc = num2str(j1);
eval(['p' jc '= [X(' jc '), Y(' jc ')]']);
end
So do not ever! Use the better 'p{1}' of the first variant instead of 'p1'

12 comentarios

developer
developer el 7 de Sept. de 2011
but i putting them in a cell i also want to name them as p1 ...p20 so that i can address them through their variable names p1, p2 etc
Fangjun Jiang
Fangjun Jiang el 7 de Sept. de 2011
See 'How can I create variables A1, A2,...,A10 in a loop?' from http://matlab.wikia.com/wiki/FAQ
Fangjun Jiang
Fangjun Jiang el 7 de Sept. de 2011
@andrei, why mat2cell? why can't p=[X Y]?
Oleg Komarov
Oleg Komarov el 7 de Sept. de 2011
Don't name variables sequentially as p1 to p20. Imagine the pain having to reference everytime 20 variables.
developer
developer el 7 de Sept. de 2011
@Komarov
But what if i put them all p1... p20 values within a structure or a cell?
Andrei Bobrov
Andrei Bobrov el 7 de Sept. de 2011
Hi Fangjun, I agree with you, but I, I thought that p {1} is more similar to p1, than p (1,:) on p1 :)
developer
developer el 7 de Sept. de 2011
@andrei
your solution is acceptable but as Komarov mentioned , if i want to put all of them in a structure like P that has p1...p20 with values of p1...p20, then i have to define all the fields one by one?
Fangjun Jiang
Fangjun Jiang el 7 de Sept. de 2011
%%
X=rand(20,1);
Y=rand(20,1);
p = mat2cell([X Y],ones(20,1),2);
f=cellstr(strcat('p',num2str((1:20)','%d')));
temp=[f p]';
P=struct(temp{:})
Andrei Bobrov
Andrei Bobrov el 7 de Sept. de 2011
f=cellstr(strcat('p',strjust(num2str((1:20)'),'left')));
Jan
Jan el 8 de Sept. de 2011
@Fangjun: Instead of creating the large intermediate array [f, p]', this is more efficient: P = cell2struct(p(:), f(:)). This is slightly faster than specifying the dimension as 3rd input of CELL2STRUCT, btw.
Oleg Komarov
Oleg Komarov el 8 de Sept. de 2011
@developer: structs and cells are fine.
Fangjun Jiang
Fangjun Jiang el 8 de Sept. de 2011
Good one, Jan! My mind was stuck with the struct().

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by