Thứ Năm, 9 tháng 9, 2010

[Lang][Matlab] Change the input argument in Matlab function

By Google search, I found 3 ways:
1. Use handle object in Matlab
- Create class that cover your argument that you want to change
- Pass to your function
2. Use Inplace parkage but it still has many limitations
3. Change the appropriate variable in caller workspace
- For scalar variable: Use two functions inputname and assignin [2]
function matlab_exp_increase(a)
A = inputname(1);
disp(['Name of variable a in caller : ' A]);
assignin('caller', A, a + 1);
end

Result:
>>a = 10
>>matlab_exp_increase(a)
a = 11
This way is useful as the variable is scalar, otherwise if this variable is a structure, matrix or array then you have to change whole variable.
- For structure, matrix or array variable:
A solution is to use evalin function, see this code section:

function matlab_exp_change_array(a)
A = inputname(1);
disp(['Name of variable a in caller : ' A]);
command = sprintf('%s(1) = 0', A);
disp(['Command will be runned in caller: ' command]);
evalin('caller', command);
end

In caller: (command windows)
>> b= [1 , 2, 3]
b =
1 2 3
>>matlab_exp_change_array(b)

Name of variable a in caller : b
Command will be runned in caller: b(1) = 0
>>b
b =
0 2 3



[1] Mathworks

Không có nhận xét nào:

Đăng nhận xét