Index in position 2 exceeds array bounds (must not exceed 1) error while comparing an array with a value

1 view (last 30 days)
Hi I am trying to compare each element in my column vector 'Energy' with the electrolyser size and then create another column vector called FLH where if the value of energy is greater than or equal to 5 then replace with 5 if it is less copy the same value in energy to FLH but I receive the error Index in position 2 exceeds array bounds (must not exceed 1) I do not know how to resolve this. Thank you for your help!

Accepted Answer

Voss
Voss on 4 Aug 2021
This error happens because the line of code in your foor loop uses the loop index i as a column index in your variables, but your for statement specifies that i goes along the length of Energy. In MATLAB, length(x) is the size of the longest dimension of x, so in this case length(Energy) is the number of rows of Energy (Energy being a column vector), not the number of columns like the code inside the loop expects.
The correct way to write such a loop would be:
FLH = zeros(size(Energy));
for i = 1:size(Energy,2)
FLH(find(Energy(:,i) >= ElectrolyserSize),i) = ElectrolyserSize;
end
You can also do it using logical indexing instead of calling the find function:
FLH = zeros(size(Energy));
for i = 1:size(Energy,2)
FLH(Energy(:,i) >= ElectrolyserSize,i) = ElectrolyserSize;
end
but you can also do logical indexing over the whole array at once instead of column-by-column:
FLH = zeros(size(Energy));
FLH(Energy >= ElectrolyserSize) = ElectrolyserSize;
However, both of these have FLH equal to 0 where Energy < ElectrolyserSize, which is not what you want. You want FLH equal to Energy where Energy < ElectrolyserSize, which you can do by explicitly saying so in another line of code:
FLH = zeros(size(Energy));
FLH(Energy >= ElectrolyserSize) = ElectrolyserSize;
FLH(Energy < ElectrolyserSize) = Energy(Energy < ElectrolyserSize);
or by initializing FLH to be equal to Energy:
FLH = Energy;
FLH(Energy >= ElectrolyserSize) = ElectrolyserSize;
However, probably the easiest way to do what you want is:
FLH = min(Energy,ElectrolyserSize);

More Answers (0)

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!