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

1 次查看(过去 30 天)
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 个评论
Dyuman Joshi
Dyuman Joshi 2023-5-24
"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

请先登录,再进行评论。

回答(1 个)

Dea M Turashvili
Dea M Turashvili 2023-5-24
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))

类别

Help CenterFile Exchange 中查找有关 Entering Commands 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by