MATLAB Answers

How to change the value of variables in base workspace within a function?

50 ビュー (過去 30 日間)
KAKI AYAM
KAKI AYAM 2019 年 6 月 28 日
コメント済み: Shameer Parmar 2019 年 7 月 1 日
Hi,
I am trying to merge a number of command lines instructions into a function. But I have noticed that instructions which I can run without errors on command lines could not be run within a function. For example, I could write to registers below at the command line such as below -
NPSN.REGISTER.LOAD.LOAD_TYPE1.write = 0;
NPSN.REGISTER.LOAD.LOAD_TYPE2.write = 1;
The same command lines will not have any effect within a function due to workspace segregations. While I could understand that concept, does Matlab provides anyway for us to change the value of these registers within a function?
These registers are actual hardware registers in the controllers which are written through Matlab.
Thanks.

  1 件のコメント

Stephen Cobeldick
Stephen Cobeldick 2019 年 6 月 28 日
It sounds like you should be writing a class rather than a function.

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

採用された回答

Shameer Parmar
Shameer Parmar 2019 年 6 月 28 日
Yes, When you use function then it has its own workspace.
Here you can use following command to assign or to execute the variable from function to base workspace..
assignin('base','NPSN.REGISTER.LOAD.LOAD_TYPE1.write','0');
assignin('base','NPSN.REGISTER.LOAD.LOAD_TYPE2.write','1');
OR try this..
evalin('base','NPSN.REGISTER.LOAD.LOAD_TYPE1.write = 0');
evalin('base','NPSN.REGISTER.LOAD.LOAD_TYPE2.write = 1');
Also check this example..
v = evalin('base', 'var')
This example extracts the value of the variable 'var' in the MATLAB base workspace and captures the value in the local variable v..

  2 件のコメント

KAKI AYAM
KAKI AYAM 2019 年 7 月 1 日
Hi Shameer,
The line below works for me. Thanks a lot!
evalin('base','NPSN.REGISTER.LOAD.LOAD_TYPE1.write = 0');
evalin('base','NPSN.REGISTER.LOAD.LOAD_TYPE2.write = 1');
But one more question. What if I need to include a local variables in the command? For example instead of the value '0' or '1', can I use a local variable instead? If yes, how shall I do it?
Thanks.
Shameer Parmar
Shameer Parmar 2019 年 7 月 1 日
try replacing '0' or '1' with your local variable names..
try with this command..
evalin('base','NPSN.REGISTER.LOAD.LOAD_TYPE1.write = LocalVarName');

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

その他の回答 (1 件)

Steven Lord
Steven Lord 2019 年 6 月 28 日
What is NPSN? Specifically, is it a handle object that has properties and methods that allow you to query and manipulate a physical hardware device? You can check this with:
isa(NPSN, 'handle')
If it is a handle object, pass it into your function as an input argument. Because handle objects have reference semantics the behavior described in the "Handle Objects Modified in Functions" section on that documentation page sounds like what you want.

  0 件のコメント

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


Translated by