Hello!
I am trying to run a code where it checks an excel table whether each cell is occupied or not. The code I have is as follow:
clear all
clc
deptime = datetime(xlsread('input data.xlsx',2,'B3:B10'),'Format',"HH:mm",'ConvertFrom','excel');
for x = 1:max(length(deptime))
if isnat(deptime(x,1)) == 1
time = 'empty';
else
time = 'occupied';
end
end
However, the code only prints the result of the last cell, while what I'm looking for is for the code to print the results of the entire loop. How can I fix it? Thank you!

댓글 수: 1

Stephen23
Stephen23 2023년 2월 27일
편집: Stephen23 2023년 2월 27일
"For loop only running once"
In fact the loop iterates multiple times. But your code overwrites TIME on every iteration, so at the end you only have the final TIME value. The standard MATLAB approach for storing data is to use indexing:
"...while what I'm looking for is for the code to print the results of the entire loop."
Print where exactly? Or do you really mean that you want to store all of those values in an array?

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

답변 (2개)

Stephen23
Stephen23 2023년 2월 27일
편집: Stephen23 2023년 2월 27일

0 개 추천

V = {'empty';'occupied'};
X = isnat(deptime(:,1));
T = V(1+X)
Dyuman Joshi
Dyuman Joshi 2023년 2월 27일
편집: Dyuman Joshi 2023년 2월 27일

0 개 추천

The code is not 'printing' the result, it is 'storing' the result in the variable time. And with every iteration of the loop, the variable 'time' is being overwritten and thus you will get the value of the last iteration after the completion of the for loop.
If you want to store each value, use a cell array or a string array. Also, length() returns a scalar value so using max() is redundant.
deptime = datetime(xlsread('input data.xlsx',2,'B3:B10'),'Format',"HH:mm",'ConvertFrom','excel');
%I have used numel() instead of length()
n=numel(deptime);
%cell array
time = cell(1,n);
%for string array, use time = strings(1,n) for pre-allocation
for x = 1:n
if isnat(deptime(x,1))
time{x} = 'empty';
else
time{x} = 'occupied';
end
end
However, you can do this without a loop as well
time = strings(n,1); %edited for the correct dimension
time(:)='occupied';
time(isnat(deptime(:,1)))='empty';

댓글 수: 2

Stephen23
Stephen23 2023년 2월 27일
편집: Stephen23 2023년 2월 27일
@Dyuman Joshi: that is a tidy no-loop solution using logical indexing. Nice.
Note that the dates appear to be only in the first column of DEPTIME (I missed this at first too), see the indexing in the OPs code: deptime(x,1)
Dyuman Joshi
Dyuman Joshi 2023년 2월 27일
Thanks for pointing it out, Stephen, I will update my solution.

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

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

질문:

2023년 2월 27일

편집:

2023년 2월 27일

Community Treasure Hunt

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

Start Hunting!

Translated by