如何创建接受字符串的向量?

时间:2012-12-27 02:18:09

标签: matlab

好的问题是,我想接收数学函数。在程序运行之前我不知道有多少。

当它运行时,我要求我将收到n个函数,并开始从输入中保存它们。

到目前为止,我有这个

function test()  
n = input('number of equations?');  
v = [1:n]  
%in an ideal world, this ^ here would allow me to put a string in each position but  
% they are not the same type and I understand that.. but how can I build a vector for saving my                functions  
%I want a vector where I can put strings in each position that is what I need   
for i=1:n  
x = input('what is the function?','s');  
v(i)=x  
end  
v   
%this would be my vector already changed with a function in each position.  
end  

1 个答案:

答案 0 :(得分:2)

如果要存储不同长度的字符串,请使用单元格数组:

v = cell(1,n);
for i=1:n   
    v{i} = input('what is the function?','s'); #% note the curly braces
end  

要将这些用作函数,请使用str2func

for i=1:n
    fh{i} = str2func(v{i});
end

fh现在是一个包含用户输入字符串定义的函数句柄的单元格数组。