importing matrix and variables of a m-file function into workspace directly and making a matrix name based on a variable string

Is it possible to import matrix and variables of a m-file function into workspace directly? please help also: i want to put a function in for-loop and there is a variable that is named: lable (string). lable, is the name of a matrix that in each loop, creates. for example when i=1 (first loop), lable='matrix1' .and when i=2,lable='matrix2' ,....
in function, a matrix creates with name of RESULT but i seriously need this name depends on 'lable', like: RESULT_lable . here i have 3 problems:
1- how could a string like lable add the name of RESULT matrix for being RESULT_lable to be a matrix in this name
2-now how could import RESULT_lable matrix directly into workspace( because where that I call this function, it self is a function too)
3-now after solving 1,2 it's needed writing if-end command, does this command true:
if exist('RESULT_lable')==0 %RESULT_lable must save in workspace
calling function
end

 Accepted Answer

1. To make a new variable name, use
Name1='matrix';
Name2='label';
NewName=[Name1,'_',Name2];
2. Don't name your varialbe as 'matrix1','matrix2',... Instead, use array or cell array so you can reference it as matrix(1),matrix(2). Search for 'How can I create variables A1, A2,...,A10 in a loop?' on this page to see the guidance. http://matlab.wikia.com/wiki/FAQ
If you really need to do it, use
assignin('base',NewName,2*pi)
3. Use exist(NewName,'var') to check if an variable with the name already exists in the workspace.

6 Comments

thanks a lot for replying
1- in this way NEWNAME is string but i want to be a data matrix name. how could convert a string to a data parameter?
2-there in no number in names of matrix. it was just examples. in each loop this matrix coming of reading a .xls file and lable is the name of that .xls file
If NewName='matrix_label',
assignin('base',NewName,2) will create a variable named 'matrix_label' in the base workspace and its value is 2.
thanks, perfect
but exist not works in function and can't see workspace when using in a function
@Mohammad: ASSIGNIN and EVALIN causes a lot of troubles again and again. Therefore I recommend to avoid the usage, especially for beginners. Please read the mentioned FAQ link.
Like Jan said, be very careful not to abuse the usage of assignin() and evalin(). If you really need to check the existing of a base workspace variable from a function, you can do:
try
evalin('base',NewName);
catch
assignin('base',NewNaew,2);
end

Sign in to comment.

More Answers (0)

Categories

Community Treasure Hunt

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

Start Hunting!