基于字符串MATLAB的名称变量 [英] Name variable based on string MATLAB

查看:97
本文介绍了基于字符串MATLAB的名称变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个由循环创建的变量.变量足够大,形式也足够复杂,我想每次使用不同的名称来保存变量时都要保存该变量.

I have a variable that is created by a loop. The variable is large enough and in a complicated enough form that I want to save the variable each time it comes out of the loop with a different name.

PM25是我的变量.但是我想将其另存为PM25_year,其中年份根据`str = fname(13:end)'更改

PM25 is my variable. But I want to save it as PM25_year in which the year changes based on `str = fname(13:end)'

PM25 = permute(reshape(E',[c,r/nlay,nlay]),[2,1,3]); % Reshape and permute to achieve the right shape. Each face of the 3D should be one day
str = fname(13:end); % The year

% Third dimension is organized so that the data for each site is on a face
    save('PM25_str', 'PM25_Daily_US.mat', '-append') 

str是一年,例如2008.因此在创建变量时,保存的变量将是PM25_2008,然后是PM25_2009,等等.

The str would be a year, like 2008. So the variable saved would be PM25_2008, then PM25_2009, etc. as it is created.

推荐答案

基于数据定义新变量不是最佳实践,但是您可以使用单元格数组更有效地存储数据.您甚至可以在单个单元格中存储大型,复杂的变量(例如PM25变量).这是您可以执行的操作:

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:

使用循环将每年的PM25数据放入单元格数组C:

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

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

结果如下:

C = { PM25_2005, PM25_2006, PM25_2007 };

现在,假设您要获取2006年的变量.这很容易(假设您没有跳过年份).数据的第一年对应于排名1,第二年对应于排名2,依此类推.因此,要查找所需年份的索引:

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};

这篇关于基于字符串MATLAB的名称变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆