Simplify code with nested if

조회 수: 1 (최근 30일)
Gaetano Pavone
Gaetano Pavone 2019년 10월 21일
댓글: the cyclist 2019년 10월 21일
I have a matrix C in which every row contains dates and times. In the fourth column months are indicated as Jun, Feb, Mar, etc... I would like to replace such abbreviations with their corresponding numeric values: Jan->1, Feb->2, etc... My first attempt is:
for i=1:size(C,1)
if C(i,4)=='Jen' C(i,4)==1;
elseif C(i,4)=='Feb' C(i,4)==2; ... etc
end
end
Is there any way for simplify this code?
  댓글 수: 2
the cyclist
the cyclist 2019년 10월 21일
What data type is C?
Gaetano Pavone
Gaetano Pavone 2019년 10월 21일
C is a 153435x34 cell

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

답변 (1개)

the cyclist
the cyclist 2019년 10월 21일
편집: the cyclist 2019년 10월 21일
% A little pretend data, where I only fill in the 4th column with a few months
C = cell(5,6);
C(:,4) = {'Jan';'Jan';'Dec';'Mar';'Jul'};
% Replace the 4th column with the numeric indices
C(:,4) = num2cell(month(datetime(C(:,4),'Format','MMM')));
  댓글 수: 2
Gaetano Pavone
Gaetano Pavone 2019년 10월 21일
C(:,4) actually is like:
C(:,4) = {"Jan";"Jan";"Dec";"Mar";"Jul"};
your code doesn't work for this format
the cyclist
the cyclist 2019년 10월 21일
Try
month(datetime([C{:,4}],"Format","MMM"))
instead. That creates a string array from the cell array of strings, which is an allowed input to the datetime function.

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

카테고리

Help CenterFile Exchange에서 Dates and Time에 대해 자세히 알아보기

태그

제품


릴리스

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by