For loop only running once
14 次查看(过去 30 天)
显示 更早的评论
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
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 个)
Dyuman Joshi
2023-2-27
编辑:Dyuman Joshi
2023-2-27
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
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)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!