Name variable based on string MATLAB

倾然丶 夕夏残阳落幕 提交于 2019-11-29 17:22:30

Defining new variables based on data isn't considered best practice, but you can store your data more efficiently using a cell array. You can store even a large, complicated variable like your PM25 variable within a single cell. Here's how you could go about doing it:

Place your PM25 data for each year into the cell array C using your loop:

for i = 1:numberOfYears
    C{i} = PM25;
end

Resulting in something like this:

C = { PM25_2005, PM25_2006, PM25_2007 };

Now let's say you want to obtain your variable for the year 2006. This is easy (assuming you aren't skipping years). The first year of your data will correspond to position 1, the second year to position 2, etc. So to find the index of the year you want:

minYear = 2005;
yearDesired = 2006;
index = yearDesired - minYear + 1;
PM25_2006 = C{index};

You can do this using eval, but note that it's often not considered good practice. eval may be a security risk, as it allows user input to be executed as code. A better way to do this may be to use a cell array or an array of objects.

That said, I think this will do what you want:

for year = 2008:2014
    eval(sprintf('PM25_%d = permute(reshape(E',[c,r/nlay,nlay]),[2,1,3]);',year));
    save('PM25_Daily_US.mat',sprintf('PM25_%d',year),'-append');
end

I do not recommend to set variables like this since there is no way to track these variables and completely prevents all kind of error checking that MATLAB does beforehand. This kind of code is handled completely in runtime.

Anyway in case you have a really good reason for doing this I recommend that you use the function assignin for this.

assignin('caller', ['myvar',num2str(1)], 63);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!