How to add the strings in three for loops

1 回表示 (過去 30 日間)
Mahmuda Ishrat Malek
Mahmuda Ishrat Malek 2018 年 9 月 5 日
what I want is to add 9terms(all k & m) for each i(1:3). h_1, h_2, h_3 each will have 9 additive terms. Example, h_1= h_1_1_1*a_1*b_1+ h_1_1_2*a_1*b_2+.......+h_1_3_3*a_3*b_3.
Thanks in advance.
ht=cell(3);
for i=1:3
for k=1:3
for m=1:3
code2=['h_',num2str(i),'=h_',num2str(i),'_',num2str(k),'_',num2str(m),'*a_',num2str(k),'*b_',num2str(m)];
ht{i}=strcat(ht,'+',code2)
eval(ht(i));
end
end
disp(ht(i));
end
  1 件のコメント
Stephen23
Stephen23 2018 年 9 月 11 日
Indexing would be much simpler and much more efficient.
The MATLAB documentation specifically warns against going exactly what you are trying to do: "A frequent use of the eval function is to create sets of variables such as A1, A2, ..., An, but this approach does not use the array processing power of MATLAB and is not recommended. The preferred method is to store related data in a single array."
Magically accessing variable names is one way that beginners force themselves into writing slow, complex, buggy code that is hard to debug:

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

採用された回答

Naman Chaturvedi
Naman Chaturvedi 2018 年 9 月 11 日
Correct code:
ht=cell(3,1);
for i=1:3
for k=1:3
for m=1:3
if (k*m==1)
code2=['h_',num2str(i),'=h_',num2str(i),'_',num2str(k),'_',num2str(m),'*a_',num2str(k),'*b_',num2str(m)];
ht{i}=[ht{i},code2];
else
code2=['h_',num2str(i),'_',num2str(k),'_',num2str(m),'*a_',num2str(k),'*b_',num2str(m)];
ht{i}=[ht{i},'+',code2];
end
end
end
disp(ht(i));
end
  3 件のコメント
Stephen23
Stephen23 2018 年 9 月 13 日
編集済み: Stephen23 2018 年 9 月 14 日
"...but I ended up with a lot more complex code"
That is because your approach is very complex. Indexing would be much simpler, and much more efficient.
Mahmuda Ishrat Malek
Mahmuda Ishrat Malek 2018 年 9 月 14 日
Can you give a short example on how I can do this sort of thing with indexing?

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by