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

1 次查看(过去 30 天)
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!

采纳的回答

Voss
Voss 2021-8-4
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);

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by