Save correct variable name in workspace

2 views (last 30 days)
I have a function in matlab.
function [MEAN STD]=result(data)
MEAN=[mean(data)];
STD=std(data);
Training_data=[MEAN STD]
savefilename=sprintf('%s',inputname(1))
save(savefilename,'Training_data')
end
i set data's filename=ET1_A_l1(imported to workspace alrdy)(ET1_A_l1=[1;2;1;3;1;4] to find the mean and std of selected data(ET1_A_l1),and save the statistical feature into .mat form as shown in below:
>>[MEAN STD]=result(ET1_A_l1)
As a result, the name of save file is ET1_A_l1.mat,and I import ET1_A_l1.mat into the workspace,it shows the 'Training_data' as the variable name.
Is there any good idea to change the variable name(Training_data) to ET1_A_l1 in workspace??
  2 Comments
Jan
Jan on 25 Nov 2012
The square brackets in MEAN=[mean(data)] are not needed and waste (a tiny piece of) time.
Image Analyst
Image Analyst on 25 Nov 2012
It's better to pass in the filename than to import it into the workspace of result. (It looks like you didn't show the code where you imported inputname into the result() function.). If inputname is a string, then inputname(1) is just the first character, and you should use inputname{1} instead.
Also, if data is more than 1D you'll get an array for MEAN and STD. If you don't want that, use mean(data(:)) and std(data(:)).

Sign in to comment.

Accepted Answer

Jan
Jan on 25 Nov 2012
Edited: Jan on 25 Nov 2012
savefilename = inputname(1); % No need for sprintf
save(savefilename, 'Data');
...
Data = load(FileName);
Now it is much safer and clearer to use Data.ET1_A_l1 instead of assigning ET1_Al1 directly. Imagine you use the name of a built-in function, e.g. "sin". Then loading this as variable directly will lead to a lot of troubles.
  2 Comments
Image Analyst
Image Analyst on 25 Nov 2012
If inputname is a string, then inputname(1) is just the first character, and you should use inputname instead. If inputname is a cell array of a bunch of filenames, then he should use inputname{1}. He should also have an extension .mat on his filename, in my opinion.
Jan
Jan on 27 Nov 2012
@Image Analyst: inputname is a function, which replies the name of the input from the caller, see doc inputname. Therefore inputname(1) does not reply one character of the name. If the variable is temporary only, inputname() replies the empty string and this must be handled in a reliable program.
Although the ".mat" is apoended automatically by save(), I'd prefer to append it explicitly also, like you. Using an absolute path might be even more important: Imagine a timer callback changes the current path during the program runs. Then it will be hard to find the written files later.

Sign in to comment.

More Answers (0)

Products

Community Treasure Hunt

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

Start Hunting!