question about how to avoid using eval

Hello, all.
I got to know that using "eval" is not efficient and may cause several problems. I have used "eval" a lot in my previous codes.
If I want to replace the following expression without using "eval", would anyone help me one this? Thank you very much.
for jjjj=1:5
for iiii=1:40
for kkkk=1:3
x1(kkkk,:) = (1:10)*kkkk;
eval(['Resp.Phi',num2str(jjjj),'.Mu',num2str(iiii),'.Respx1(kkkk,:) = x1(kkkk,:);']);
end
end
end

 採用された回答

Walter Roberson
Walter Roberson 2016 年 11 月 22 日

0 投票

Resp.(sprintf('Phi%d',jjjj).(sprintf('Mu%d',iiii)),.Respx1(kkkk,:) = x1(kkkk,:);

5 件のコメント

Baozai
Baozai 2016 年 11 月 22 日
Thank you, Walter.
But it seems it doesn't work properly. I got the following error in Matlab (matlab 2014b)
Undefined variable "sprintf" or class "sprintf".
Walter Roberson
Walter Roberson 2016 年 11 月 22 日
Resp.(sprintf('Phi%d',jjjj)).(sprintf('Mu%d',iiii)),.Respx1(kkkk,:) = x1(kkkk,:);
KSSV
KSSV 2016 年 11 月 22 日
I think comma before .Respx1 is not needed. It throws error.
Walter Roberson
Walter Roberson 2016 年 11 月 22 日
You are right,
Resp.(sprintf('Phi%d',jjjj)).(sprintf('Mu%d',iiii)).Respx1(kkkk,:) = x1(kkkk,:);
Baozai
Baozai 2016 年 11 月 22 日
This works, thank you very much.

サインインしてコメントする。

その他の回答 (1 件)

KSSV
KSSV 2016 年 11 月 22 日

0 投票

iwant = cell(5,40,3) ;
for jjjj=1:5
for iiii=1:40
for kkkk=1:3
x1(kkkk,:) = (1:10)*kkkk;
iwant{jjjj,iiii,kkkk}= ['Resp.Phi',num2str(jjjj),'.Mu',num2str(iiii),'.Respx1(kkkk,:) = x1(kkkk,:);'] ;
end
end
end

3 件のコメント

Baozai
Baozai 2016 年 11 月 22 日
Hi, KSSV:
Thank you very much for replying. But I am afraid this is not what I want.
Resp is actually a structure that contains different vectors. The Structure is like:
Resp.Phi1.Mu1.Respx1 = [1 2 3 4 5 6 7 8 9 10; 2 4 6 8 10 12 14 16 18 20; 3 6 9 12 15 18 21 24 27 30]
Resp.Phi1.Mu2.Respx1 = [1 2 3 4 5 6 7 8 9 10; 2 4 6 8 10 12 14 16 18 20; 3 6 9 12 15 18 21 24 27 30]
Resp.Phi1.Mu3.Respx1 = [1 2 3 4 5 6 7 8 9 10; 2 4 6 8 10 12 14 16 18 20; 3 6 9 12 15 18 21 24 27 30]
..........
Resp.Phi5.Mu40.Respx1 = [1 2 3 4 5 6 7 8 9 10; 2 4 6 8 10 12 14 16 18 20; 3 6 9 12 15 18 21 24 27 30]
And the values in these matrices are different since the statements inside the loop are more complicated than listed here.
KSSV
KSSV 2016 年 11 月 22 日
編集済み: KSSV 2016 年 11 月 22 日
Resp = struct ;
for jjjj=1:5
for iiii=1:40
for kkkk=1:3
x1(kkkk,:) = (1:10)*kkkk;
% iwant{jjjj,iiii,kkkk}= ['Resp.Phi',num2str(jjjj),'.Mu',num2str(iiii),'.Respx1(kkkk,:) = x1(kkkk,:);'] ;
end
for llll = 1:3
Resp(jjjj).Phi1(iiii).Mu1(llll).Respx1 = x1 ;
end
end
end
Resp(1).Phi1(1).Mu1
Baozai
Baozai 2016 年 11 月 22 日
This one also works, thank you very much for your help.

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

質問済み:

2016 年 11 月 22 日

コメント済み:

2016 年 11 月 22 日

Community Treasure Hunt

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

Start Hunting!

Translated by