How to retrieve mat file data? - matlab

I have a mat file with 10 (columns) x 3 (rows) of data and I would like to retrieve these data to produce some readable output via certain functions. For example, the first column of data is 1 0 0 and the output will be Yes.
May I know how can I perform the first step, which is how to retrieve/read the data from the mat file which saved in laptop?

Assuming the name of your '.mat' file as 'xyz.mat' and the variable stored in .mat file had same name as the file.
load('xyz.mat') % loads xyz.mat into workspace.
if xyz(:,1)==[1;0;0],
answer='yes'
end
Note: Here I have assumed that array xyz was stored as xyz.mat , if the array name was different from filename given to the .mat file then you will have to use the array name in the if statement . e.g. if you stored an array named abcd as xyz.mat then when you use load('xyz.mat') the array gets loaded with its original name (abcd) and not the file name xyz

Related

how to load multiple files from directory into an array using matlab?

i have a directory that includes some .mat files , i want to load all these files into an array .
i tried something like this :;
x1=load('C:\Users\me\OneDrive\Desktop\project\a\first_file.mat')
x2=load('C:\Users\me\OneDrive\Desktop\project\a\second_file.mat')
... and so on for all the files in the directory , and at the end i want to have an array such that:
arr(1)=x1 ...
how can i access the directory and load all of the files at the same time into an array ?
ps: i tried using path before and dir but then i got this error :
error using eval , undefind function 'workspacefun' for input
arguments of type struct
thank you in advance.
The load function loads what variables are in the .mat file with their real names into the current workspace. If you assign x as an output for load, the variables names appear as fields of a struct named x. For example, if first.mat contains v1, then, x = load('first.mat') will result in a x = struct with fields: v1.
So, in your case, assuming that you are sure that each .mat file contains a single variable, you can write the following loop to load all .mat files into a cell array arr.
fds = fileDatastore('*.mat', 'ReadFcn', #load); % assume same folder
files = fds.Files;
for i = 1:length(files)
% convert one-field struct into array, store in "arr"
arr{i} = struct2array(load(files{i}));
end
And each arr{i} will now contain a variable, say vi, in lexicographic order. If the .mat file contains more than one variable, this code will break. If the files are in another folder, you can use their actual path and extension like this fileDatastore('path', 'ReadFcn', #load, 'FileExtensions','.mat').

How do you call a function that takes in a MAT file, manipulate the data in that file, and create a new textfile with that same MAT file name?

The filename in question is a MAT file that contains elements in the form of "a - bi" where 'i' signifies an imaginary number. The objective is to separate the real, a, and imaginary, b, parts of these elements and put them into two arrays. Afterwards, a text file with the same name as the MAT file will be created to store the data of the newly created arrays.
Code:
function separate(filename)
realArray = real(filename)
imagArray = imag(filename)
fileIDname = strcat(filename, '.txt')
fileID = fopen(fileIDname, 'w')
% more code here - omitted for readability
end
I am trying to run the above code via command window. Here's what I've tried so far:
%attempt 1
separate testFileName
This does not work as the output does not contain the correct data from the MAT file. Instead, realArray and imagArray contains data based on the ascii characters of "testFileName".
e.g. first element of realArray corresponds to the integer value of 't', the second - 'e', third - 's', etc. So the array contains only the number of elements as the number of characters in the file name (12 in this case) instead of what is actually in the MAT file.
%attempt 2
load testFileName
separate(testFileName)
So I tried to load the testFileName MAT variable first. However this throws an error:
Complex values cannot be converted to chars
Error in strcat (line 87)
s(1:pos) = str;
Error in separate (line xx)
fileIDname = strcat(filename, '.txt')
Basically, you cannot concatenate the elements of an array to '.txt' (of course). But I am trying to concatenate the name of the MAT file to '.txt'.
So either I get the wrong output or I manage to successfully separate the elements but cannot save to a text file of the same name after I do so (an important feature to make this function re-usable for multiple MAT files).
Any ideas?
A function to read complex data, modify it and save it in a txt file with the same name would look approximately like:
function dosomestuff(fname)
% load
data=load(fname);
% get your data, you need to knwo the variable names, lets assume its call "datacomplex"
data.datacomplex=data.datacomplex+sqrt(-2); % "modify the data"
% create txt and write it.
fid=fopen([fname,'.txt'],'w');
fprintf(fid, '%f%+fj\n', real(data.datacomplex), imag(data.datacomplex));
fclose(fid);
There are quite few assumptions on the data and format, but can't do more without extra information.

How to load mat files w/ different names?

I have different mat files w/ distinct names. So I am using a function whose input is the mat file. I used "varargin" to enable the function to take different files.
function bestfunc(varargin)
data = load(varargin, '-mat');
end
when I try to call the function like
bestfunc('matrix777')
Matlabe comes up w/ this error:
Error using load
Argument must contain a string.
Any ideas?
you have to get the names of the files. You can use dir() to do that.
dir('*.mat') % will return information about all .mat files in the folder
The output is a struct with more information for each file. TO get the names try
names=struct2cell(dir('*.mat'));
names=names(1,:);
now names is a cellarray with the names of all *.mat files of your folder. TO load data from each go for
for i=1:length(names)
bestfun(names{i});
end
Since you're only passing one argument, you don't need varargin, which is used when you may have a variable number of arguments to a function.
Just use a normal variable name like matname:
function bestfunc(matname)
data = load(matname, '-mat');
end
Then call it as you did before:
bestfunc('matrix777')

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 a file in MATLAB with a variable filename in a loop [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
Save mat file from MATLAB
How to tell MATLAB to open and save specific files in the same directory
I have a set of CSV files and need to extract data to obtain plots. I use the following code to generate a variable file name in a loop and accordingly get the desired data.
P = dir('*.csv');
for m = 1:length(P)
P(m).data = csvread(P(m).name);
end
I now want to modify these CSV files (change the data values in the CSV files) before obtaining the desired data and then save these files to Excel format (.xls) within the loop.
Something like
for i = 1:length(P(m).data)
if P(m).data(i,1)< value1
P(m).data(i,2) = 0;
end
save P(m).xls P(m).data -ascii; % Gives error "save 'P(m).data' is not a valid variable name."
end
How do I save a file in Excel (.xls) format with a variable filename obtaining data from array in a loop?
Check out the MATLAB documentation for the save() function
You need to use the function-call syntax to use variable file names:
save(P(m).xls, P(m).data, '-ascii');
Edit: you seem to have new errors. I can see two things:
your P variable is a struct array, so it has more than 1 element -- save() can save only one file at a time;
2 xls is not a file of your struct, which has a name field.
To save your data, it will probably resemble this:
for m = 1 : length(P),
save(P(m).name, P(m).data, '-ascii');
end
If you want to replace the extension to avoid overwriting your files (I assume xls is what you wanted), this should do the trick:
for m = 1 : length(P),
name = P(m).name;
name = name(1:find(name,'.'));
name = [name '.xls'];
save(name, P(m).data, '-ascii');
end