How to simplify code with multiple variable names?

1 view (last 30 days)
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 Comments
Stephen23
Stephen23 on 5 Aug 2022
"How to simplify code with multiple variable names?"
By using arrays rather than multiple variable names.

Sign in to comment.

Accepted Answer

Jon
Jon on 5 Aug 2022
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 Comments
dpb
dpb on 6 Aug 2022
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...

Sign in to comment.

More Answers (0)

Categories

Find more on Resizing and Reshaping Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!