Same code line works outside but not inside for loop.

조회 수: 1 (최근 30일)
Rudolf
Rudolf 2021년 5월 3일
댓글: Rudolf 2021년 5월 3일
I have a code which i don't understand why acts differently outside compared to inside a for loop.
With this code:
filename = ('elspot-prices_2019_hourly_nok – Kopi.xlsx');
[~,~,raw] = xlsread(filename);
hourValues{1} = raw(any(strcmp(raw(:,2),["00 - 01"])>0,2),14);
hourValues{2} = raw(any(strcmp(raw(:,2),["01 - 02"])>0,2),14);
hourValues{3} = raw(any(strcmp(raw(:,2),["02 - 03"])>0,2),14);
I'll get the result: hourValues 1x3 cell, where each cell have an array of hour values.
I need this for 24 hours, so a loop would be great. But when like this:
for i=0:23
if i < 10
text1 = "0" + string(i);
else
text1 = string(i);
end
if i+1 < 10
text2 = "0" + string(i+1);
else if i+1 == 24
text2 = "00";
else
text2 = string(i+1);
end
end
fulltext = text1 + " - " + text2;
hourValues{i+1} = raw(any(strcmp(raw(:,2),[fulltext])>0,2),14); %<--Why don't this line work?
end
i'll get: hourValues 1x24 cell which all is empty. Just showing [] in each of the cells.
(I've tried all kinds of combination for variabel fulltext, with and without [ ], and also both as string or char.)
Any idea why this don't work?
(Edit: xlsx file added)
  댓글 수: 5
Rudolf
Rudolf 2021년 5월 3일
Now file is included. :)
I like your code Scott, but for some reason i get a string from the if-else statement, while a char from your code. Maybe string/char both works for all purposes anyway so i shouldn't pay attention to that?
Rudolf
Rudolf 2021년 5월 3일
Thanks for reply Scott and dpb.
@dpb Will see if i can learn how to convert to datetime and use readtable. It sounds more convenient.

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

채택된 답변

Benjamin Großmann
Benjamin Großmann 2021년 5월 3일
편집: Benjamin Großmann 2021년 5월 3일
The problem is, that the xlsx file contains protected spaces ( char(160) ) and you are comparing to normal spaces.
Quick and very dirty solution is:
fulltext = text1 + char(160) + "-" + char(160) + text2;
hourValues{i+1} = raw(any(strcmp(raw(:,2),[fulltext])>0,2),14); % should work now
@dpb mentions it in the comments and I would recommend it too: Use readtable and convert your xlsx data to datetime.
  댓글 수: 1
Rudolf
Rudolf 2021년 5월 3일
Thank you very much Benjamin! I didn't know about that, nice to learn.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Data Type Conversion에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by