How can i code for problems which have range

조회 수: 6 (최근 30일)
prem kumar
prem kumar 2022년 1월 26일
댓글: prem kumar 2022년 1월 26일
hello there friends previously i have posted here and its been a great help...Today i want to ask regarding how to code for range values ...Example :-0.3<x<0.3.I understood that i need to use for or If loop for this and the general syntax for loop is
for variable =c:g:h
statements
end
so i tried something like this
for dn=1:1:365
if (-0.3>sdelta)&&(sdelta<0.3)
fprintf('number of days : %d',dn)
end
end
but i couldnt get the desired output.Can anyone help me out or guide me ?Thank You.

채택된 답변

DGM
DGM 2022년 1월 26일
편집: DGM 2022년 1월 26일
I'm not sure if this is exactly where you're going with your example, but let's say you have a vector and you want to print a message for each element that falls within a range. You could do that with a loop like you show.
roomtemperature = [38 41 16 26 34 21 32 12 27 36]; % average temp per day
comfortablerange = [22 27];
for k = 1:numel(roomtemperature)
iscomfortable = roomtemperature(k)>=comfortablerange(1) ...
&& roomtemperature(k)<=comfortablerange(2);
if iscomfortable
fprintf('The room temp was a comfortable %d°C on day %d\n',roomtemperature(k),k)
end
end
The room temp was a comfortable 26°C on day 4 The room temp was a comfortable 27°C on day 9
If you want to do something other than print messages, it may be better to extract this information as logical vectors and use that to perform some desired tasks by indexing. This obviates the loop.
iscomfortable = roomtemperature>=comfortablerange(1) ...
& roomtemperature<=comfortablerange(2);
avgcomfortabletemps = mean(roomtemperature(iscomfortable))
avgcomfortabletemps = 26.5000
minuncomfortabletemps = min(roomtemperature(~iscomfortable))
minuncomfortabletemps = 12
maxuncomfortabletemps = max(roomtemperature(~iscomfortable))
maxuncomfortabletemps = 41
  댓글 수: 3
DGM
DGM 2022년 1월 26일
sdelta = 4*rand(1,365)-2; % test data [-2 2]
targetangle = [-0.3 0.3];
% create logical mask
gooddays = sdelta >= targetangle(1) ...
& sdelta <= targetangle(2);
% count nonzero elements of mask
numberofgooddays = nnz(gooddays)
numberofgooddays = 59
prem kumar
prem kumar 2022년 1월 26일
friend do you mind if you could explain the lines so it gives me a better understanding?

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by