Dealing with strings and numbers in a for loop.
17 次查看(过去 30 天)
显示 更早的评论
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
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).
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)
Z = groupsummary(TT,'DT','monthofyear','sum')
采纳的回答
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 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!