How to summarize this code?

2 次查看(过去 30 天)
BN
BN 2019-10-27
回答: Guillaume 2019-10-28
I have one cell in my workplace namly precips. this cell contains 34 3d arrays (please see picture attached). I want to have each 3d array as a variable in my workplace in order to do some other calculations. using this code, I achieve this purpose. but I want to know if any other shorter code available. I have attached the screenshot of my Matlab workplace and command line.
thank you
precip_1982 = precips{1, 1};
precip_1983 = precips{2, 1};
precip_1984 = precips{3, 1};
precip_1985 = precips{4, 1};
precip_1986 = precips{5, 1};
precip_1987 = precips{6, 1};
precip_1988 = precips{7, 1};
precip_1989 = precips{8, 1};
precip_1990 = precips{9, 1};
precip_1991 = precips{10, 1};
precip_1992 = precips{11, 1};
precip_1993 = precips{12, 1};
precip_1994 = precips{13, 1};
precip_1995 = precips{14, 1};
precip_1996 = precips{15, 1};
precip_1997 = precips{16, 1};
precip_1998 = precips{17, 1};
precip_1999 = precips{18, 1};
precip_2000 = precips{19, 1};
precip_2001 = precips{20, 1};
precip_2002 = precips{21, 1};
precip_2003 = precips{22, 1};
precip_2004 = precips{23, 1};
precip_2005 = precips{24, 1};
precip_2006 = precips{25, 1};
precip_2007 = precips{26, 1};
precip_2008 = precips{27, 1};
precip_2009 = precips{28, 1};
precip_2010 = precips{29, 1};
precip_2011 = precips{30, 1};
precip_2012 = precips{31, 1};
precip_2013 = precips{32, 1};
precip_2014 = precips{33, 1};
precip_2015 = precips{34, 1};

采纳的回答

Shubham Gupta
Shubham Gupta 2019-10-28
You can try to create structure for the data of different years:
for i = 1:length(precips)
precip.(['y',num2str(i+1981)]) = precips{i,1};
end
Now, if you want to access data with any specific year say 2000. You can just type:
Req_data = precip.y2000;
I hope it helps!

更多回答(1 个)

Guillaume
Guillaume 2019-10-28
As demonstrated by the later questions (here and here), this was a very bad idea in the first place. Creating numbered or sequentially named variables always make the rest of the code more complicated not easier. You had a perfectly useful cell array, it is dead easy to iterate over it, there is no need to split it into separate variables:
for idx = 1:numel(precips)
dosomethingwith(precips{idx})
end

类别

Help CenterFile Exchange 中查找有关 Performance and Memory 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by