Matrix segmentation into files in Matlab - 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.

Related

How do I write a MATLAB code that edits another MATLAB file (.m)?

I have two files, Editor.m and Parameters.m. I want to write a code in Editor.m that when run does the following task:
reads Parameters.m
searches for a line in it (e.g. dt=1)
replaces it with something else (e.g. dt=0.6)
saves Parameters.m.
So, at the end of this process, Parameters.m will contain the line dt=0.6 instead of dt=1, without me having edited it directly.
Is there a way to do this? If so, how?
You can use regexprep to replace the value of interest.
% Read the file contents
fid = fopen('Parameters.m', 'r');
contents = fread(fid, '*char').';
fclose(fid);
% Replace the necessary values
contents = regexprep(contents, '(?<=dt=)\d*\.?\d+', '0.6');
% Save the new string back to the file
fid = fopen('Parameters.m', 'w');
fwrite(fid, contents)
fclose(fid)
If you can guarantee that it will only ever appear as 'dt=1', then you can use strrep instead
contents = strrep(contents, 'dt=1', 'dt=0.6');

How to get number from file in matlab?

In my program I want to save the counter value. Like 1 and if the counter increased then 1 will be replace with 2 like that. I created a file test.txt and manually entered a number 1, in the directory and used this code to read that number.
f=fopen('test.txt');
cno=fread(f);
cno
fclose(f);
But the value of cno is in ASCII I guess because its saved like this in file.
I try to used functions like parseInt but didn't work.
Please tell me how to write as well as read a number from file.
Also if there is any other way possible to save that counter value instead of file. I want to retain value even If I close matlab code that's why I am saving it to the file.
There are a couple methods for this. If you don't need to ensure compatibility with external programs, then MATLAB's save and load commands should be more than sufficient.
A basic example:
a = 5;
save('test.mat', 'a');
clear a
load('test.mat');
disp(a)
See the documentation for save for syntax information.
As a general note I would advise calling load with an output declared, which will load all of the variables in your saved *.mat file into a structure, preventing them from overwriting existing data in your workspace.
Using test.mat from the previous example:
mydata = load('test.mat');
disp(mydata.a)
EDIT: Now, if you wanted to store this to a generic file, the most common method would be to use fprintf and fscanf:
a = 5;
fID = fopen('test.txt', 'w+');
fprintf(fID, '%u', a);
fclose(fID);
clear a
fID = fopen('test.txt', 'r')
a = fscanf(fID, '%u');
fclose(fID);

load txt dataset into matlab in a matrix structure

I need to read a txt dataset and do some analytics by matlab. the structure of the txt file is like this:
ID Genre AgeScale
1 M 20-26
2 F 18-25
So, I want to load this txt file and build a matrix. I was wondering if someone could help me with this. I used fopen function but it gives me a single array not a matrix with 3 columns.
MATLAB has an interactive data importer. Just type uiimport in the command window. It allows you to:
Name the variable based on heading as shown in your example. You can also manually change them.
Specify variable (column) type, e.g. numeric, cell array of strings, etc.
Auto generate an import script for next use (if desired)
If it works for you then congratulations, you don't need to waste hours to write an data import script :)
Function fopen only returns the file ID and not the content of the file. Once you open the file you use the file ID to read line by line and then parse each line with strsplit using space as the delimiter.
Here's one simple way of doing so:
fid = fopen('textfile.txt');
tline = fgetl(fid);
n = 1;
while ischar(tline)
data(n,:) = strsplit(tline(1:end-1),' ');
n=n+1;
tline = fgetl(fid);
end
fclose(fid);
Keep in mind that the matrix data is type string and not numeric, so if you want to use the numeric values of your dataset, you'll need to take a look at the functions str2num (str2double in newer versions) and strtok to split the AgeScale strings with delimiter '-'.

Saving a Matrix in 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.

how to read wav files one after other from the same folder in Matlab

I am trying to write a program where i have to read a wav file, extract some features from it and save them and then go and pick the next file repeat the same procedure. the number of wave files to be picked are more than 100. Can someone help me how to read wavfiles one after another. (say the files are named e1.wav,e2.wav and so on). someone please help me
The dir command is quite helpful here. It either displays the whole content of a directory but you can also specify a glob to just return a sub-set of files, e.g. dir('*.wav'). This returns an struct-array containing file information such as name, date, bytes, isdir and so on.
To get started, try the following:
filelist = dir('*.wav');
for file = filelist
fprintf('Processing %s\n', file.name);
fid = fopen(file.name);
% Do something here with your file.
fclose(fid);
end
Edit 1: Change the double-quotes to single-quotes (thx to user1540393).
Edit 2 (Suggested by amro): If a processing result has to be stored per file,
I often use the following pattern. I usually pre-allocate an array, a struct array or
a cell array of the same size as the filelist. Then I use an integer index to iterate
over the file list, which I can also use to write the output. If the information to be
stored is homogeneous (e.g. one scalar per file), use an array or a struct array.
However, if the information differs from file to file (e.g. vectors or matrices of different size) use a cell array instead.
An example using an ordinary array:
filelist = dir('*.wav');
% Pre-allocate an array to store some per-file information.
result = zeros(size(filelist));
for index = 1 : length(filelist)
fprintf('Processing %s\n', filelist(index).name);
% Read the sample rate Fs and store it.
[y, Fs] = wavread(filelist(index).name);
result(index) = Fs;
end
% result(1) .. result(N) contain the sample rates of each file.
An example using a cell array:
filelist = dir('*.wav');
% Pre-allocate a cell array to store some per-file information.
result = cell(size(filelist));
for index = 1 : length(filelist)
fprintf('Processing %s\n', filelist(index).name);
% Read the data of the WAV file and store it.
y = wavread(filelist(index).name);
result{index} = y;
end
% result{1} .. result{N} contain the data of the WAV files.