how to compare string from .txt file with workspace in Matlab - matlab

I'm having a .txt file like this:
structure
a = title
c1 = A.B.C
endstructure
I want to read this to matlab and then check if in my workspace already exists a structure named A.B.C. if so, then I want to save data from this structure to variable c1.
I have problem with proper parsing the line c1 = A.B.C and then comparing it with workspace.
any help appreciated.
explanation - - - - - -
in my workspace there is a structure A.B.C. = [0 1 2 3 5 8]
in my txt file I write c1 = A.B.C, and that is the name. I want in my program to check if this name matches some already existing data with this name in the workspace. if so, assign this data to a variable c1 and leave c1 in the workspace.

To determine if your variable already exists in the Matlab workspace, you can use matlab exist function. It would be a little awkward in your situation though as you can only check to see if variable 'A' exists. You could then nest it further and see if the variable has the specified field. It could look like this:
if( exist('A','var') && isfield(A,'B') && isfield(A.B,'C') )
%do something
end

You can use evalin with the syntax evalin('base',expression,catch_expr) with expression the right side of your '=' sign.
It's not really efficient but it avoid you to have to parse the structure name. In catch_expr you can set a flag telling not to do the assignment.
Just use assignin after that to assign the value in 'c1'. 'c1' is a here string so it's easy to put it in a loop with different names.

Related

Loading multiple .mat files containing the same variable name and changing the variable names simultaneously?

So I have a directory that has many .mat files:
apples.mat, oranges.mat, bananas.mat, grapes.mat, apricots.mat, pears.mat, pineapple.mat
All of these .mat files has a variable name "calories" assigned a value. How do I load all of these .mat files simultaneously in MATLAB and change the variables for each one from calories to calories_(fruit name) so that I can have all the variable values in the workspace to play with?
For example, I want to load apples.mat and change its variable name from calories to calories_apple, then load oranges.mat and change is variable name from calories_orange, etc. without doing it all manually.
I know it's something along the lines of creating a string with the different fruit names, and the indexing along the string to load a file and change its variable from variable to variable_%s with the %s indicating the fruit content generated along the loop. It's a big mess for me, however, I don't think I'm structuring it right. Would anyone care to help me out?
I would load each .mat file in sequence and put each of the corresponding calories as a separate field being all combined into a single struct for you to access. Given the directory of where these .mat files appear, do something like this:
%// Declare empty structure
s = struct()
folder = '...'; %// Place directory here
%// Get all MAT files in directory
f = dir(fullfile(folder, '*.mat'));
%// For each MAT file...
for idx = 1 : numel(f)
%// Get absolute path to MAT file - i.e. folder/file.mat
name = fullfile(folder, f(idx).name);
%// Load this MAT file into the workspace and get the calories variable
load(name, 'calories');
%// Get the name of the fruit, are all of the characters except the last 4 (i.e. .mat)
fruit_name = f(idx).name(1:end-4);
%// Place corresponding calories of the fruit in the structure
s.(['calories_' fruit_name]) = calories;
end
You can then access each of the calories like so using dot notation:
c = s.calories_apple;
d = s.calories_orange;
...
...
... and so on.
I am assuming that you do not mean to include the parenthesis in calories_(fruit name). I am also assuming there are no other .mat files in your current directory. This should do the trick:
theFiles = dir('*.mat');
for k = 1:length(theFiles)
load(theFiles(k).name, 'calories');
eval(['calories_' theFiles(k).name(1:length(theFiles(k).name)-4) ' = calories;'])
clear calories
end
Let me know if this helps or not.
EDIT
As, rayryeng points out. The use of eval is, apparently, a bad practice. So, if you are willing to change the way you are thinking about the problem, I suggest you use a structure. In which case, rayryeng's response would be an acceptable answer, even though it does not directly answers your original question.

saving matlab file (.mat) with dynamic name

for m = 1:length(lst_region)
out=cellfun(#(x) str2double(x(1:strfind(x,'_')-1)),lst_region(m));
str=[num2str(out(1)) '.mat'];
save ( str ,distance);
end
Error using save
Argument must contain a string. Line 3
I want to save files like '1.mat' '2.mat' etc.. but i have error can you please help me to fix it
If distance is a variable in your workspace, you will have to call save(str, 'distance');. You have to enter the name of the variable, not the variable itself.

Matlab - Error using save Cannot create '_' because '_____' does not exist

I have some data in a cell array,
data2={[50,1;49,1;26,1];...
[36,2;12,2;37,2;24,2;47.3,2];}
and names in another cell array,
names2={'xxx/01-ab-07c-0fD3/0';'xxx/01-ab-07s-0fD3/6';}
I want to extract a subset of the data,
data2_subset=data2{1,:}(:,1);
then a temporary file name,
tempname2=char(names2(2));
an save the subset to a text file with
save (tempname2, 'data2_subset', '-ASCII');
But I get this error message: _
Error using save
Cannot create '6' because 'xxx/01-ab-07s-0fD3' does not exist.
To try to understand what is happening, I created a mock dataset with simpler names:
names={'12-05';'14-03'};
data={[50,1;29,1;25,1];[35,2;22,2;16,2;38,2];[40,3;32,3;10,3;44,3;43,3];};
data_subset=data{1,:}(:,1);
tempname=char(names(2));
save (tempname, 'data_subset', '-ASCII');
in which case the save command works properly.
Unfortunately I still do not understand what the problem is in the first case. Any suggestions as to what is happening, and of possible solutions?
MATLAB is interpreting the the forward slashes (/) as directory separators and 6 as the intended file name (your second example doesn't have this slash problem).
Since the relative directory tree xxx/01-ab-07s-0fD3/ doesn't exist, MATLAB can't create the file.
To solve the problem, you can either create the directories beforehand using mkdir():
>> pieces = strsplit(tempname2,'/');
>> mkdir(pieces{1:2});
>> save(tempname2, 'data2_subset', '-ASCII');
or replace the / with some other benign symbol like _:
>> tempname3= strrep(tempname2,'/','_');
>> save (tempname3, 'data2_subset', '-ASCII');
(which works for me).

save svm models to file matlab

I have 31 models an I want to save each one in a specific file
this is my matlab function
formatspec='model%d'
for k = 1:length(libsvmFiles)
baseFileName = libsvmFiles(k).name;
fullFileName = fullfile(myFolder, baseFileName);
[labels train]=libsvmread(fullFileName);
model=svmtrain(labels,train, '-t 2 -h 0');
file=sprintf(formatspec,k);
save file model;
but the problem is only the first file is saved and its name is 'file' tha's mean the value of the variable file is not evaluated
how can I solve this problem ?
As many Matlab functions, save can be used in function form (save(...)) or in command form (save ...). In the command form that you use, all the arguments are interpreted as strings. That means
save file model
is equivalent to
save('file', 'model')
For the second argument that is correct, because you want to refer to the variable with the name "model". For the first argument it is wrong, because you want to refer to the file name contained in the variable file. The correct syntax to use is therefore
save(file, 'model')
You're missing the parens for the save function. The model variable also needs to be listed as a string since you need to tell the save function the name of the variable, not the variable itself. See Matlab's documentation.
save(file, 'model');
Additionally you don't have an end to your for loop shown, which normally would just throw an error -- however later code might cause this loop to instead only run once. Otherwise you should check your libsvmFiles variable as it might be only length 1 or not be an array.

loading a variable from a .mat file into a differently named variable

Say I have a .mat file with several instances of the same structure, each in a different variable name.
I want to process each instance found in a file (which I find using whos('-file' ...). I was hoping that load would let me specify the destination name for a variable so that I didn't have to worry about collisions (and so that I didn't have to write self-modifying code a la eval).
The brute force way to do this appears to be creating a helper function that, using variables with names that hopefully don't conflict with the .mat contents, does something like:
Does a whos on the file to get the contained names.
Iteratively load each contained structure.
Uses eval to assign the loaded structure into, say, a cell array (where one column of the array contains the .mat file's structure names and a corresponding column with the actual contents of each structure from the .mat file).
Is there no more elegant way to accomplish the same thing?
Of course you can! Just use load with an output argument.
x = 1;
save foo;
ls = load('foo.mat');
ls.x
you can load the data in a MAT file into a structure
ws = load('matlab.mat');
the fields of the structure ws will be the variables in the MAT file. You can then even have a cell array of structures
ws{1}=load('savedWorkSpace_1.mat');
ws{2}=load('savedWorkSpace_2.mat');
Example
>> x = 1;
>> save ws_1;
>> x = 2;
>> y = 1;
>> save ws_2
>> clear
>> ws{1} = load('ws_1.mat')
>> ws{2} = load('ws_2.mat')
>> ws{1}.x
x = 1
>> ws{2}.x
x = 2