How to add the strings in three for loops
조회 수: 2 (최근 30일)
이전 댓글 표시
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
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
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
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Environment and Settings에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!