How to add the strings in three for loops

조회 수: 2 (최근 30일)
Mahmuda Ishrat Malek
Mahmuda Ishrat Malek 2018년 9월 5일
댓글: Mahmuda Ishrat Malek 2018년 9월 14일
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 CenterFile Exchange에서 Environment and Settings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by