Effacer les filtres
Effacer les filtres

The for loop always replaces the value previous. How do I store all the values produced from the for loop?

1 vue (au cours des 30 derniers jours)
I have this for loop with an if statement and every time I run it, it displays both values but the one displayed on top is not saved, but I need to be able to have both of them stored in an array. I tried putting them into an empty array but I dont quite understand how to. Any help would be appreciated. Thanks! This code is just finding outliers, but I need to do something with those outliers but I cant when only one is saved and replacing the other.
Data = [923 916 932 927 908 931 953 926 919 963];
B = sort(Data,'ascend');
n = numel(B);
xmin = B(1);
xmax = B(n);
Q1 = round(.25*(n+1));
Q3 = round(.75*(n+1));
atQ1 = B(Q1);
atQ3 = B(Q3);
IQR = atQ3 - atQ1;
MO = 1.5*IQR;
A = [];
for i = 1:length(B)
if B(i) <=(atQ1-MO) || B(i) >=(atQ3+MO)
A(i) = B(i);
disp(A(i));
end
end
  1 commentaire
Dyuman Joshi
Dyuman Joshi le 24 Mai 2023
"it displays both values but the one displayed on top is not saved, but I need to be able to have both of them stored in an array"
It saves both the values.
If that is not the output you want, please specify the desired output.
Data = [923 916 932 927 908 931 953 926 919 963];
B = sort(Data,'ascend');
n = numel(B);
xmin = B(1);
xmax = B(n);
Q1 = round(.25*(n+1));
Q3 = round(.75*(n+1));
atQ1 = B(Q1);
atQ3 = B(Q3);
IQR = atQ3 - atQ1;
MO = 1.5*IQR;
%Growing an array is not a good practice, pre-allocate
A = zeros(size(B));
for i = 1:length(B)
if B(i) <=(atQ1-MO) || B(i) >=(atQ3+MO)
A(i) = B(i);
disp(A(i))
end
end
953 963
A
A = 1×10
0 0 0 0 0 0 0 0 953 963

Connectez-vous pour commenter.

Réponses (1)

Dea M Turashvili
Dea M Turashvili le 24 Mai 2023
disp in this case will only display one value at a time because you are specifically indexing with i. However, this doesn't mean that A did not store all the values. If you want to see them all every time, simply write disp(A) instead of disp(A(i))

Catégories

En savoir plus sur Entering Commands 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!

Translated by