For loop only running once
14 views (last 30 days)
Show older comments
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 Comment
Stephen23
on 27 Feb 2023
Edited: Stephen23
on 27 Feb 2023
"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?
Answers (2)
Dyuman Joshi
on 27 Feb 2023
Edited: Dyuman Joshi
on 27 Feb 2023
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 Comments
Stephen23
on 27 Feb 2023
Edited: Stephen23
on 27 Feb 2023
@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)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!