简体   繁体   English

MATLAB函数可重新分配未定义数量的变量的值

[英]MATLAB function to reassign values of undefined number of variables

I want to write a MATLAB function that can take an undefined number of variables, change their values, and output them under the same names. 我想编写一个MATLAB函数,该函数可以接受未定义数量的变量,更改其值,并以相同的名称输出它们。 I got part way there if I don't mind listing the variables twice: 如果我不介意两次列出变量,那么我就可以做到这一点:

function [varargout]=testing(varargin)
    for i=1:nargin
        varargout{i}=varargin{i}*2;
    end
end

and

x=5;
y=3;
z=6;
[x,y,z]=testing(x,y,z);

But I don't want to list the variable names twice. 但是我不想两次列出变量名。 Is there anyway I can call the function like this instead? 无论如何,我可以像这样调用该函数吗?

testing(x,y,z);

I tried using inputname, but I couldn't figure out how to make it work. 我尝试使用输入名,但是我不知道如何使它起作用。

Blindly adjusting values across workspaces is highly unadvisable and can lead to hard to detect bugs and make the code difficult to maintain. 极不建议在工作空间之间盲目地调整值,这可能导致难以发现错误,并使代码难以维护。 Arguments against this essentially mirror arguments against global variables . 对此的争论实质上是对全局变量的争论 It will be far more reliable to explicitly control the data you want to manipulate. 显式控制要处理的数据将更加可靠。 Yes, this will probably require you to store your data differently. 是的,这可能会要求您以其他方式存储数据。

For example, you can use a structure : 例如,您可以使用以下结构

function testcode()
mydata.a = 1;
mydata.b = 2;
mydata.c = 3;
mydata.d = 4;

mydata = multiplydata(mydata, 2);
disp(mydata)
end

function [datastruct] = multiplydata(datastruct, n)
varnames = fieldnames(datastruct);
for ii = 1:length(varnames)
    datastruct.(varnames{ii}) = datastruct.(varnames{ii})*n;
end
end

Which outputs: 哪个输出:

>> testcode
    a: 2
    b: 4
    c: 6
    d: 8

This isn't really any functionally different than using varargin / varargout , but if you write your code in such a way that you're utilizing structures from the beginning, you don't have to deal with the extra unpacking step (eg x = varargin{1} , etc.). 这实际上与使用varargin / varargout功能上没有什么不同,但是如果您以从一开始就使用结构的方式编写代码,则不必处理额外的拆包步骤(例如x = varargin{1}等)。


If, for whatever reason, you absolutely must blindly adjust your variables (which, again, please don't), then you can use assignin : 如果出于某种原因,您绝对必须盲目地调整变量(同样,请不要这样做),则可以使用assignin

function testcode()
a = 1;
b = 2;
c = 3;
d = 4;

multiplydata(2, a, b, c, d);
fprintf('a: %u\nb: %u\nc: %u\nd: %u\n', a, b, c, d)
end

function multiplydata(n, varargin)
for ii = 1:length(varargin)
    varname = inputname(ii + 1);
    assignin('caller', varname, varargin{ii}*n)
end
end

Which returns: 哪个返回:

>> testcode
a: 2
b: 4
c: 6
d: 8

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM