How can I override a value with an input?

6 ビュー (過去 30 日間)
Andrew
Andrew 2014 年 8 月 8 日
回答済み: Geoff Hayes 2014 年 8 月 8 日
I have a list of variables with values, but I want to be able to override one of those values with an input. To demonstrate:
function [output] = test(variable, value)
x = 2;
y = 3;
q = 10;
end
And let's say my input is (x, 5). Other than using a bunch of if statements, is there a way to make x = 5?
  2 件のコメント
Azzi Abdelmalek
Azzi Abdelmalek 2014 年 8 月 8 日
This is not clear, variable and value are not used in your function
Andrew
Andrew 2014 年 8 月 8 日
That's the thing, I don't know how to use them. 'variable' should match one of the ones declared in the code (i.e. x, y, or q) and 'value' is whatever value that variable should be. So if my input is (y, 10), then I want to set y = 10.
I'm explaining this poorly, I apologize, but I'm not quite sure how else to describe it.

サインインしてコメントする。

採用された回答

A Jenkins
A Jenkins 2014 年 8 月 8 日
Some of it depends on how much you want to protect against "bad" values or variable names being passed. But here is a simple trick:
function [output] = test(variable, value)
mydata.x = 2;
mydata.y = 3;
mydata.q = 10;
mydata.(variable)=value
end
........................................................
>> test('x',5)
mydata =
x: 5
y: 3
q: 10
  1 件のコメント
Andrew
Andrew 2014 年 8 月 8 日
Yeah, that should work, thanks!

サインインしてコメントする。

その他の回答 (1 件)

Geoff Hayes
Geoff Hayes 2014 年 8 月 8 日
Could also just compare the input variable to a set of pre-defined "matches"
function [output] = test(variable, value)
x = 2;
y = 3;
q = 10;
if ischar(variable) && isvector(variable)
if strcmp(variable,'x')
x = value;
elseif strcmp(variable,'y')
y = value;
elseif strcmp(variable,'q')
q = value;
end
end
The above will guard against the case where variable is not a string, and is one of x, y, and q.

カテゴリ

Help Center および File ExchangeMATLAB についてさらに検索

タグ

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by