Saving a Matrix in MatLab - matlab

I have a MatLab program that generates a large 1000x1000 matrix. How can I save this matrix for use in future programs. Ideally, I want to save it as a particular variable. Here is the code that I am using.
function A = generateSPDmatrix(n)
A = rand(n,n); % generate a random n x n matrix
A = A+A';
A = A*A';
A = A + n*eye(n);
end

If you want to use it in future Matlab programs, you could do it like this:
save('A.mat', 'A');
To load, just do it like this:
load('A.mat');

% the file path is current path.
save('A.txt', 'A','-ascii');
% save to your file path
save('D:\test.txt','m','-ascii')
'D:\test.txt': file name and path
'm': your matrix
'-ascii': 8-digit ASCII format
See the matlab Help. Search the save(Save workspace variables to file) function
save(filename, variables, format) saves in the specified format: '-mat' or '-ascii'. You can specify the format option with additional inputs such as variables, '-struct' , '-append', or version.

Related

Separate definition of constant values and dependent parameters in Matlab

In my code, I have a lot of constant values and parameters that take significant space in my code.
For example in C++, I would make a header and a separate file where I would define these parameters as, e.g., "const-type" and share the header with main or other .cpp files.
How do you keep such structuring in MATLAB, is it worth it?
An example: Coefficients.m looks as follows:
classdef coefficients
properties(Constant)
% NIST data
A_N = 28.98641;
end
end
Another file: Gas.m where I would like to use A_N looks as follows:
function Gas()
clear all
clc
import Coefficients.* % Does not work
% A simple print
Values.A_N % Does not work
coefficients.A_N % Does not work
Constant.A_N % Does not work
end
Ok so assuming the class coefficients defined as:
classdef coefficients
properties(Constant)
% NIST data
A_N = 28.98641;
end
end
This code must be saved in a file named coefficients.m (The class name and file name have to match to avoid weird effect sometimes).
Then assuming the following Gas.m file:
function Gas()
% Usage with "disp()"
disp('The A_N coefficient taken from NIST data is:')
disp(coefficients.A_N)
% Usage with fprintf
fprintf('\nFrom NIST data, the coefficient A_N = %f\n',coefficients.A_N)
% Usage in calculation (just use it as if it was a variable/constant name
AN2 = coefficients.A_N^2 ;
fprintf('\nA_N coefficient squared = %.2f\n',AN2)
% If you want a shorter notation, you can copy the coefficient value in
% a variable with a shorter name, then use that variable later in code
A_N = coefficients.A_N ;
fprintf('\nA_N coefficient cubed = %.2f\n',A_N^3)
end
Then running this file (calling it from the command line) yields:
>> Gas
The A_N coefficient taken from NIST data is:
28.98641
From NIST data, the coefficient A_N = 28.986410
A_N coefficient squared = 840.21
A_N coefficient cubed = 24354.73
Or if you simply need to access the coefficient in the Matlab console:
>> coefficients.A_N
ans =
28.98641
Now all these examples assume that the class file coefficient.m is visible in the current Matlab scope. For Matlab, it means the file must be in the MATLAB search path (or the current folder works too).
For more info about what is the Matlab search path and how it works you can read:
What Is the MATLAB Search
Path?
Files and Folders that MATLAB
Accesses
In your case, I would make a folder containing all these sorts of classes, then add this folder to the Matlab path, so you never have to worry again about individual script, function or program calling for it.
See this link for tips on using a class definition for this. Highlights of the tips are:
Properties can be accessed directly to get the value
Properties can be added that give the units of the constant (highly advised!)
Comments can be added that act as help text for the constants
The doc command automatically creates a reference page for this classdef
E.g.,
classdef myconstants
properties(Constant)
% g is the gravity of Earth
% (https://en.wikipedia.org/wiki/Gravity_of_Earth)
g = 9.8;
g_units = 'm/s/s';
% c is the speed of light in a vacuum
c = 299792458;
c_units = 'm/s';
end
end
>> help myconstants.g

Deriving 'y' matrix and sampling rate as the parameters of audiowrite function i.e audiowrite(filename,y,Fs)

I am a bit lost in understanding how audiowrite function derives 'y', and 'Fs', the last two parameters of the function. I looked at some of the examples provided by Matlab, and they seem to work fine. The first set of codes is an example by Matlab which returns 'y' and 'Fs' value.
load handel.mat
filename = 'handel.wav';
audiowrite(filename,y,Fs);
Now, I have written a similar set of codes to work with a .csv file. Knowing the input argument for load function can only be in .mat format, I have written some codes in the following format.
csvread('bgst.csv');
save bgst.mat
load bgst.mat;
filename = 'bgst.wav';
audiowrite(filename,y,Fs);
But, in this case I am getting the error message: Undefined function or variable 'y'(or, Fs if I have defined y in the line w/ csvread function). So, why audiowrite is not creating 'y', and 'Fs' by itself as in the previous case. BTW, my .csv file is 999998x4 double. And, any more information to help me out, please let me know.
When you do:
load handel.mat
You are loading a MAT-file containing variables into the workspace. This is what initializes y and Fs, which are used as input arguments to audiowrite. You can see this using the whos function to see the variables being created:
>> clear all % Removes all current variables
>> load handel.mat
>> whos
Name Size Bytes Class Attributes
Fs 1x1 8 double
y 73113x1 584904 double
The variable y contains the matrix of audio data with sampling rate Fs. You have to create these yourself for your data and pass them to audiowrite.

How to automatically save files in Matlab?

I have a neural network and am generating figures and I wish to save those figures automatically with the filename as the training function and the hidden layer size, as well as the percentage correct
I have the following
... trainFcn=trainscg
This changes between a couple of options: scg, rp, lm, etc
I also have the
hiddenLayerSize=[10 10 10]
These values also change often.
I run my neural network and output a confusion matrix:
figure, plotconfusion(nnOutput, target)
I then do
saveas(gcf, trainFcn+hiddenLayerSize)
This does not work when I add the variables like that and also fails when I put a comma instead of a plus. How can I make this saveas work and make the filename my variables? I don't need to have the accuracy in the filename but if I can then it'd be great.
Your method does not work because the function expects a string as a filename but trainFcn+hiddenLayerSize is not one. Try the following:
% convert size vector to a string
sizeString = sprintf('%dx', hiddenLayerSize);
sizeString = sizeString(1:end-1); % removes the trailing x
% auto-generate your filename
filename = sprintf('%s_%s', func2str(trainFcn), sizeString);
saveas(gcf, filename);
This assumes that you have defined trainFcn like trainFcn = #trainscg; or something similar.

Matrix segmentation into files in Matlab

I have a very large matrix (M X N). I want to divide matrix into 10 equal parts (almost) and save each of them into a separate file say A1.txt, A2.txt, etc. or .mat format. How can I do this ?
Below is a code to divide a matrix into 10 equal parts and data_size is (M / 10).
for i=1:10
if i==1
data = DATA(1:data_size,:);
elseif i==10
data = DATA((i-1)*data_size+1:end,:);
else
data = DATA((i-1)*data_size+1: i*data_size,:);
end
save data(i).mat data
% What should I write here in order to save data into separate file data1.mat, data2.mat etc.
end
You said you wanted it in either txt format or mat format. I'll provide both solutions, and some of this is attributed to Daniel in his comment in your post above.
Saving as a text file
You can use fopen to open a file up for writing. This returns an ID to the file that you want to write to. After this, use fprintf and specify the ID to the file that you want to write to, and the data you want to write to this file. As such, with sprintf, generate the text file name you want, then use fprintf to write data to your file. It should be noted that writing matrices to fprintf in MATLAB assume column major format. If you don't want your data written this way and want it done in row-major, you need to transpose your data before you write this to file. I'll provide both methods in the code depending on what you want.
After you're done, use fclose to close the file noting that you have finished writing to it. Therefore, you would do this:
for i=1:10
if i==1
data = DATA(1:data_size,:);
elseif i==10
data = DATA((i-1)*data_size+1:end,:);
else
data = DATA((i-1)*data_size+1: i*data_size,:);
end
filename = sprintf('A%d.txt', i); %// Generate file name
fid = fopen(filename, 'w'); % // Open file for writing
fwrite(fid, '%f ', data.'); %// Write to file - Transpose for row major!
%// fwrite(fid, '%f ', data); %// Write to file - Column major!
fclose(fid); %// Close file
end
Take note that I space separated the numbers so you can open up the file and see how these values are written accordingly. I've also used the default precision and formatting by just using %f. You can play around with this by looking at the fprintf documentation and customizing the precision and leading zero formatting to your desire.
Saving to a MAT file
This is actually a more simpler approach. You would still use sprintf to save your data, then use the save command to save your workspace variables to file. Therefore, your loop would be this:
for i=1:10
if i==1
data = DATA(1:data_size,:);
elseif i==10
data = DATA((i-1)*data_size+1:end,:);
else
data = DATA((i-1)*data_size+1: i*data_size,:);
end
filename = sprintf('A%d.mat', i); %// Generate file name
save(filename, 'data');
end
Take note that the variable you want to save must be a string. This is why you have to put single quotes around the data variable as this is the variable you are writing to file.
You can use
save(['data' num2str(i) '.mat'], 'data');
where [ ] is used to concatenate strings and num2str to convert an integer to a string.

Saving image using MATLAB

I made a program in MATLAB to generate images with different specifications, but each time I change one of theses specifications I had to re-save the image under a different name and path. So, I made a for loop to change these specifications, but I don't know how I can make MATLAB save the generated image with different names and different paths...
How can I write a program to make MATLAB save multiple generated images with different names and different paths as a part of for–loop?
Put something like this at the end of your loop:
for i = 1:n
<your loop code>
file_name=sprintf('%d.jpg',i); % assuming you are saving image as a .jpg
imwrite(your_image, file_name); % or something like this, however you choose to save your image
end
If you want to save JPEG, PNG etc., then see #AGS's post. If you want to save FIG files, use
hgsave(gcf, file_name)
instead of the imwrite line. There's also
print('-djpeg', file_name) %# for JPEG file (lossy)
print('-dpng', file_name) %# for PNG file (lossless)
as an alternative for imwrite.
Since I wanted to save the plots in my loop in a specific folder in my present working directory (pwd), I modified my naming routine as follows:
for s = 1:10
for i = 1:10
<loop commands>
end
end
% prints stimuli to folder created for them
file_name=sprintf('%s/eb_imgs/%0.3f.tif',pwd,s(i)); % pwd = path of present working
% directory and s(i) = the value
% of the changing variable
% that I wanted to document
file_name = /Users/Miriam/Documents/PSYC/eb_imgs/0.700.tif % how my filename appears
print('-dtiff', '-r300', file_name); % this saves my file to my desired location
matlab matlab-path