How to simplify code with multiple variable names?

조회 수: 1 (최근 30일)
cjnavee
cjnavee 2022년 8월 5일
댓글: dpb 2022년 8월 6일
For example, a code like this:
ma1 = trapz(ea1(r1:ir1),ty(r1:ir1));
ma2 = trapz(ea2(r2:ir2),ty(r2:ir2));
ma3 = trapz(ea3(r3:ir3),ty(r3:ir3));
ma4 = trapz(ea4(r4:ir4),ty(r4:ir4));
ma5 = trapz(ea5(r5:ir5),ty(r5:ir5));
But, if I have even more variables, then is there a shortcut or simpler method to syntax them?
  댓글 수: 2
dpb
dpb 2022년 8월 5일
Yeah, don't create the sequentially-numbered arrays ea, r and ir in the first place.
What specifically should use instead will depend upon where they're coming from, but since each ea is being addressed as a vector, then simply storing ea as a 2D array might work if they're different variables at each and there are the same number of observations for each.
Are the X spacings (ea) nonuniform one must presume for each?
Are the number of elements in each subset the same?
So many questions, so little detaill...
Stephen23
Stephen23 2022년 8월 5일
"How to simplify code with multiple variable names?"
By using arrays rather than multiple variable names.

댓글을 달려면 로그인하십시오.

채택된 답변

Jon
Jon 2022년 8월 5일
You can use arrays to hold your data. So one approach would be to use arrays:
ma - n by 1
ea - k by n
r - n by 1
ir n by 1
then you could loop through the values
n = 5;
ma = zeros(n,1);
for i = 1:n
ma(i) = trapz(ea(r(i):ir(i),i),ty(r(i):ir(i)));
end
  댓글 수: 2
cjnavee
cjnavee 2022년 8월 6일
Thank you!
dpb
dpb 2022년 8월 6일
NB: that trapz is internally vectorized to operate by columns -- if you can arrange your subsections appropriately, you may well be able to take advantage of that -- why I asked about the details...

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Operators and Elementary Operations에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by