How to fix my for loop to continue to the next value in the list when condition is false?
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Hi,
Could anyone help me with how I could fix my code so it continues to check the next value in the list (Besparingslistan) if the condition in the IF-statement is false?
Also, right now I get the error "Index exceeds the number of array elements (13)." How can I fix it?
(The "Besparingslistan" is a list with the size 169x3 built up with different combinations of 13 different customers in the first two columns and a savingsvalue in the third column. While Kund_i_tur and Turkonfig are column vectors with the customers, aka (1:1:13). )
f = size(Besparingslistan,1);
a = size(Besparingslistan,2);
for forstatur = 1:f
for andratur = 1:a
if Kund_i_tur(f)~= Kund_i_tur(a)
Turkonfig = {f a};
end
end
end
4 commentaires
Image Analyst
le 6 Juil 2020
What does this show in the command window:
whos Besparingslistan
whos Kund_i_tur
It seems like either (the poorly named) f or a is larger than the length of Kund_i_tur.
Réponses (1)
Arjun
le 6 Déc 2024
Hi @Amanda,
I see that you have a piece of code and you are facing an error “Index exceeds the number of array elements (13)” and want to fix it.
The issue is that since you mentioned that “kund_i_tur” is a column vector having 13 rows, but you are trying to index it using “f” which can have values ranging from 1 to 169 and hence this error. To fix that, a simple if statement to check the range of “f” is required. Apart from this the logic to fetch “forstatur” and “andratur” as first and second column of the row is not correct. The correct logic to fetch them would be:
“forstatur = Besparingslistan(forstatur, 1)”
“andratur = Besparingslistan(forstatur, 2)”
Kindly refer to the code below for better understanding:
% Initialize a cell array or matrix to store the pairs
Turkonfig = [];
% Iterate over rows of Besparingslistan
for i = 1:size(Besparingslistan, 1)
forstatur = Besparingslistan(i, 1);
andratur = Besparingslistan(i, 2);
% Ensure indices do not exceed Kund_i_tur size
if forstatur <= length(Kund_i_tur) && andratur <= length(Kund_i_tur)
if Kund_i_tur(forstatur) ~= Kund_i_tur(andratur)
% Append the pair to the list
Turkonfig = [Turkonfig; forstatur, andratur];
end
end
end
% Display the list of all qualifying pairs
disp('Qualifying pairs:');
disp(Turkonfig);
Kindly refer to the documentation of “for” loop for better understanding:https://www.mathworks.com/help/releases/R2021a/matlab/ref/for.html
I hope this will help!
0 commentaires
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!