Storing of output in a for loop

조회 수: 2 (최근 30일)
Ismail Zabeeullah
Ismail Zabeeullah 2022년 5월 2일
댓글: Jon 2022년 5월 2일
I need to count the number of values in specific ranges of 0-50,50-100,100-150 etc. I did try to run the code however, I am unable to store the output for each range. Could you please let me know a solution for it?
A=xlsread('Values.xlsx','Sheet1','A2:A3204');
count=0;
for x=0:50:7500;
for i=1:3202;
if A(i)>x & A(i)<x+50
count=count+1;
end
t(1,:)=count;
end
x=x+50;
end

답변 (1개)

Jon
Jon 2022년 5월 2일
편집: Jon 2022년 5월 2일
A=xlsread('Values.xlsx','Sheet1','A2:A3204');
count=0;
% assign x
x = 0:50:7500;
% preallocate vector to hold counts
numCounts = numel(x);
t = zeros(numCounts,1);
for k = 1:numel(x)
count = 0;
for i=1:3202
if A(i)>=x(k) && A(i)<x(k)+50 % make sure you don't overlap or leave out any
count=count+1;
end
t(k)=count;
end
end
  댓글 수: 3
Jon
Jon 2022년 5월 2일
You could also do this in one line using MATLAB's histcounts function
t = histcounts(A,[x x(end)+50]);
Jon
Jon 2022년 5월 2일
Sorry for all of the edits on the original answer, nothing changed too much, I guess I hadn't had my coffee yet and I kept seeing minor formatting and other cosmetic errors (removing unecessary semicolons etc)

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by