如何将dynamic创build的向量返回到工作区?

你好我试图写一个函数读取某种types的电子表格,并从它的数据dynamic地创build向量,然后返回到工作区。

我的xlcs是由行构成的,在第一行中有一个string应该成为向量的名称,其余的行包含组成向量的数字。

这是我的代码:

function [ B ] = read_excel(filename) %read_excel a function to read time series data from spreadsheet % I get the contents of the first cell to know what to name the vector [nr, name]=xlsread(filename, 'sheet1','A2:A2'); % Transform it to a string name_str = char(name); % Create a filename from it varname=genvarname(name_str); % Get the numbers which will make up the vector A=xlsread(filename,'B2:CT2'); % Create the vector with the corect name and data eval([varname '= A;']); end 

据我可以告诉vector是corefully创build,但我没有ideea如何将其返回到工作区。

优选地,解决scheme应该能够返回一个不确定的vector数,因为这只是一个原型,我希望函数一次返回用户select的vector的数量。

更确切地说,vectorvarname被创build,我可以在脚本中使用它,如果我添加:

 eval(['plot(',varname,')']) 

它将绘制vector,但为了我的目的,我需要将vectorvarname返回到工作区,以在脚本运行后保留。

因为这是一个函数,所以你需要将你创build的variables传递给一个输出variables。 我build议你通过一个结构来完成,因为你不知道你想要输出多less个variables。 因此,将这个eval线改为:

 % Create the vector with the correct name and data eval(['B.' varname '= A;']); 

现在你应该有一个名为B的结构体,它在运行带有与dynamic创build的variables名称相同的字段名称的函数后保留在工作区中。 比如说一个varnameX ,你现在可以在你的工作空间中以BX身份访问它。

但是你应该仔细考虑这个代码devise,dynamic创buildvariables名是不太可能成为最好的方法。

我想你正在寻找evalin

 evalin('base', [varname '= B;']); 

(这不会正常工作,但请继续阅读)

不过,我强烈build议不要使用它。

它往往不那么容易出错,通常被认为是良好的做法,事实上通常具有可预测的function结果。

从各种angular度来看,拥有一个处理超出其自身范围的数据的函数是非常不可取的,更不用说将不可预知的数据分配给不可预知的variables名。 这是不必要的难以debugging,维护,并不是很灵活。 另外,在其他函数中使用这个函数并不是一个不知道你的函数的人会认为是这样的。

为什么不使用smoething就像一个结构:

 function B = read_excel(filename) ... B.data = xlsread(filename,'B2:CT2'); B.name = genvarname(name_str); end 

那么你总是有相同的名称作为输出( B ),其中包含相同的数据( B.data ),其name也可以用来dynamic引用其他的东西(即A.(B.name) )。

evalin的替代evalin是函数assignin 。 它不如evalin强大,但确实是你想要的 – 在工作区中分配一个variables。

用法:

 assignin('base', 'var', val)