Simplify code with nested if
4 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Antworten (1)
the cyclist
am 21 Okt. 2019
Bearbeitet: the cyclist
am 21 Okt. 2019
% 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 Kommentare
the cyclist
am 21 Okt. 2019
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.
Siehe auch
Kategorien
Mehr zu Characters and Strings finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!