Dealing with strings and numbers in a for loop.

조회 수: 7(최근 30일)
Ashfaq Ahmed
Ashfaq Ahmed 2022년 3월 22일
편집: Stephen23 2022년 3월 22일
Hi guys,
I have
April2003 = 55;
April2004 = 279;
April2005 = 311;
.
.
.
.
April20020 = 119
How can I run a for loop that sums up all these data for me? I tried this, but it doesn't work -
for i = 2003:2020
APRIL_total = sum('April',num2str(i))
end
Can anyone please help me?
  댓글 수: 1
Stephen23
Stephen23 2022년 3월 22일
편집: Stephen23 2022년 3월 22일
"I have..." badly designed data that forces me into writing slow, complex, inefficient code when I try to access it in a loop.
The cause is forcing meta-data into the variable names.
"Can anyone please help me?"
You can help you, by not forcing meta-data into variable names. Use arrays, just like MATLAB is designed for, to store both your data (number values) and your meta-data (dates).
A TIMETABLE might be agood choice for your data:
DT = datetime([2003;2003;2004;2005;2020;2020],[1;4;4;4;1;4],1);
V = [23;55;279;311;64;119];
TT = timetable(DT,V)
TT = 6×1 timetable
DT V ___________ ___ 01-Jan-2003 23 01-Apr-2003 55 01-Apr-2004 279 01-Apr-2005 311 01-Jan-2020 64 01-Apr-2020 119
Z = groupsummary(TT,'DT','monthofyear','sum')
Z = 2×3 table
monthofyear_DT GroupCount sum_V ______________ __________ _____ 1 2 87 4 4 764

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

채택된 답변

Steven Lord
Steven Lord 2022년 3월 22일
Having variables with numbered names like this is a code smell. See this Answers post for an explanation of why they smell and alternatives you should use instead.

추가 답변(0개)

범주

Find more on Matrices and Arrays in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by