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 ExchangeStructures についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by