For loop only running once

14 ビュー (過去 30 日間)
Nisrina Ariseno
Nisrina Ariseno 2023 年 2 月 27 日
編集済み: Dyuman Joshi 2023 年 2 月 27 日
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 日
V = {'empty';'occupied'};
X = isnat(deptime(:,1));
T = V(1+X)

Dyuman Joshi
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
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.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by