Array math: The logical indices contain a true value outside of the array bounds.

1 view (last 30 days)
I have 1-dimensional vectors, x and y. To return the x value corresponding to the maximum y value, I can use:
x(y==max(y))
Cool!
Now I need to do this for several 1-dimensional y vectors. I could make a loop. But how could I use an array instead?
Similarly, I was able to use this function to return multiple amplitudes in a array, 1 for each y vector.
amplitude = abs( max(y) - min(y) )/2;

Answers (1)

KALYAN ACHARJYA
KALYAN ACHARJYA on 9 Apr 2023
Edited: KALYAN ACHARJYA on 9 Apr 2023
The y value can be store in a cell array and use the cellfun to get the result. Here is an example-
#Without Loop
x=[10 12 13 7 0 9];
y={[50 11 9 19 10 49],[30 11 9 19 10 49],[10 11 9 79 10 49]};
dat=cellfun(@(n)x(n==max(n)),y)
dat = 1×3
10 9 7
#Using loop
n=length(y);
dat=zeros(1,n);
for i=1:n
dat(i)=x(y{i}==max(y{i}));
end
dat
dat = 1×3
10 9 7
Avoiding a loop in all cases is no better decision, instead it can be used loops with proper pre-allocation. Use as per your requirements.

Categories

Find more on Loops and Conditional Statements 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!