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

 채택된 답변

Andrei Bobrov
Andrei Bobrov 2011년 9월 7일

0 개 추천

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

developer
developer 2011년 9월 7일
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 2011년 9월 7일
See 'How can I create variables A1, A2,...,A10 in a loop?' from http://matlab.wikia.com/wiki/FAQ
Fangjun Jiang
Fangjun Jiang 2011년 9월 7일
@andrei, why mat2cell? why can't p=[X Y]?
Oleg Komarov
Oleg Komarov 2011년 9월 7일
Don't name variables sequentially as p1 to p20. Imagine the pain having to reference everytime 20 variables.
developer
developer 2011년 9월 7일
@Komarov
But what if i put them all p1... p20 values within a structure or a cell?
Andrei Bobrov
Andrei Bobrov 2011년 9월 7일
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 2011년 9월 7일
@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 2011년 9월 7일
%%
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 2011년 9월 7일
f=cellstr(strcat('p',strjust(num2str((1:20)'),'left')));
Jan
Jan 2011년 9월 8일
@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 2011년 9월 8일
@developer: structs and cells are fine.
Fangjun Jiang
Fangjun Jiang 2011년 9월 8일
Good one, Jan! My mind was stuck with the struct().

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Structures에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by