필터 지우기
필터 지우기

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