0

您好,我正在尝试编写一个函数,该函数读取某种类型的电子表格并根据其数据动态创建向量,然后将所述向量返回到工作区。

我的 xlcs 由行构成,第一行有一个字符串,它应该成为向量的名称,其余行包含构成向量的数字。

这是我的代码:

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

据我所知,向量是正确创建的,但我不知道如何将其返回到工作区。

最好该解决方案应该能够返回不确定的 nr 个向量,因为这只是一个原型,我希望该函数一次返回用户选择的 nr 个向量。

更准确地说,创建了向量 varname,如果我添加,我可以在脚本中使用它:

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

它将绘制矢量,但出于我的目的,我需要将矢量 varname 返回到工作区以在脚本运行后持续存在。

4

3 回答 3

2

I think you're looking for evalin:

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

(which will not work quite right as-is; but please read on)

However, I strongly advise against using it.

It is often a lot less error-prone, usually considered good practice and in fact very common to have predictable outcomes of functions.

From all sorts of perspectives it is very undesirable to have a function that manipulates data beyond its own scope (i.e., in another workspace than its own), let alone assign unpredictable data to unpredictable variable names. This is unnecessarily hard to debug, maintain, and is not very portible. Also, using this function inside other functions does not what someone who doesn't know your function would think it does.

Why not use smoething like a structure:

function B = read_excel(filename)

    ...

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

Then you always have the same name as output (B) which contains the same data (B.data) and whose name you can also use to reference other things dynamically (i.e., A.(B.name)).

于 2013-04-09T08:15:28.620 回答
1

因为这是一个函数,所以您需要将创建的变量传递给输出变量。我建议您通过结构来完成,因为您不知道要预先输出多少变量。因此,将eval行更改为:

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

现在,您应该有一个名为的结构B,在运行函数后,该结构在工作区中保持不变,其字段名称等于您动态创建的变量名称。例如,您varname现在X可以在工作区中以B.X.

但是您应该非常仔细地考虑这种代码设计,动态创建变量名称不太可能是最好的方法。

于 2013-04-09T08:12:17.623 回答
1

An alternative to evalin is the function assignin. It is less powerfull than evalin, but does exacty what you want - assign a variable in a workspace.

Usage:

assignin('base', 'var', val)
于 2013-04-09T09:30:41.693 回答