Index in position 2 exceeds array bounds (must not exceed 1) error while comparing an array with a value
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Ritika Srinivasan
le 4 Août 2021
Commenté : Ritika Srinivasan
le 5 Août 2021
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!
0 commentaires
Réponse acceptée
Voss
le 4 Août 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);
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!