I have a *.mat file with some tables included.I want to load each table one by one and then plot it so that the figures of each table update on one single figure .Please tell me if i am not clear ...I though this code must have been enough but it is not working when i asked it to load one table ... please guide me why and how i should improve the code ?
Thank you
filename = uigetfile
load(filename)
c=who('Hs*' ) % all the tables which starts with Hs
cc=numel(c) % count the number of desired tables in MAT file which we loaded before
for i=1: cc
b=load(filename,c(i));
contour(b,60)
end
I can see at least three errors in your code.
After the first load you don't clear the mat file, and hence all tables are still in the memory.
c is a cell array, and you shoud index it by using brackets (i.e. c{i}).
By default each plot in a figure deletes the previous one. Writing figure(); hold on; before the for loop shoud fix your problem.
Related
I am trying to load a file in Matlab. But I am a bit confused about the best way to do it.
The file has 3 columns and looks like the screenshot below:
This file I can load very quickly by doing load('c').
However, I had to add 2 NaNs on the bottom row.
The original file actually looks like the file below:
Now if I do load('c') on the file below I get the error:
Error using load
Unable to read file 'c'. Input must be a MAT-file or an ASCII file containing numeric
data with same number of columns in each row.
Of course I can use ImportData to import this file, but it is just soooo slow to import it.
Any suggestions?
You should be able to use c = readtable('c'). This should automatically change the empty entries to "NaN" by default, but if not, there is a way to set that in the options.
If I have a file that is tricky to import (prior to readtable()...that made things a lot easier in the last few years), I will often use the Import Data tool (if its a really big file you can make a mock-up of the complicated file so it loads faster) then change all the import settings as I would want it, then where the green check says "Import Selection" use the black drop down arrow to select "Generate Function." This will give you the coded way of setting everything up to get the file in just the way you want it.
load() is better suited for reading in previously saved '.mat' files that were created in Matlab.
Here's a low-level approach, which might be faster than other methods:
filename = 'c'; % name of the file
N = 3; % number of columns
fid = fopen(filename, 'r'); % open file for reading
x = fscanf(fid, '%f'); % read all values as a column vector
fclose(fid); % close file
x = [x; NaN(N-mod(numel(x)-1,N)-1, 1)]; % include NaN's to make length a multiple of N
x = reshape(x, N, []).'; % reshape to N columns in row-major order
I have 100 data files in a folder called "Experiment1", and I need to take all of the data from them and put them into a single matrix. Each data file contains 15 columns and 40 rows of data.
The order in which the files are in the folder is arbitrary. It doesn't matter in what order they get put into the combined matrix.
I've written some code using dlmread that will do the job:
for i = 1:100
%% Read in the relevant file.
filename = ['File_' int2str(i) '.dat']
Data = dlmread(fullfile(pwd, 'Experiment1',filename));
%% Put all the data I need in a separate matrix
NeededData(1+((i-1)*40):i+((i-1)*40)-i+40,1:15) = Data(:,1:15);
end
However, there are two things I don't like about my code.
The files have random names at present, and I'd need to manually change all their names to "File_1.dat", "File_2.dat", etc.
The code is cumbersome and hard to read.
How could I do things better?
Since you've fixed the problem of defining the name of the files to be read with dir, you can improve the way you add the read data (Data) to the output matrix (NeededData).
You can sumultaneously read the input files and add the data to the output matrix by inserting the call to dlmread directly in the assignment statement:
files=dir('*.dat');
n_files=length(files)
% Initialize the output matrix as empty
NeededData_0=[]
for i=1:n_files
% Simultaneously read input file and assign data to the output matrinx
NeededData_0=[NeededData_0;dlmread(files(i).name)]
end
In case you prefer working with the inides (as in your origina approach), since you know in advance that all the files have the same (40) number of rows) you can simplify the notation as follows:
files=dir('*.dat');
n_files=length(files)
% Define the number of rows in each inout file
n_rows=40;
% Define the number of colums in each inout file
n_col=15;
NeededData_2=nan(n_rows*n_files,n_col)
% Define the sequence of rows
r_list=1:n_rows:n_rows*n_files
for i=1:3
Data=dlmread(files(i).name)
NeededData_2(r_list(i):r_list(i)+n_rows-1,:)=Data
end
Hope this helps.
Using the suggestion to use dir present in the answers I have made the following code, which is clearly an improvement on my earlier effort. I would welcome further improvements, or suggestions for alternative approaches.
files = dir('*.dat');
for i = 1:length({files.name})
%% Read in the relevant file.
Data = dlmread(files(i).name);
%% Put all the data I need in a separate matrix
NeededData(1+((i-1)*40):i+((i-1)*40)-i+40,1:15) = Data(:,1:15);
end
I have two Column txt file every Column contain the speed on dc motor. I want to plot every Column with the time and compaire the two curves.
I tried this code, but not working:
fid = fopen('C:\Users\Hussam Yonis\Desktop\recive.txt','r');
KK = fscanf(fid,'%f %f',[2,50]);
t=0:0.05:0.05*length(a(:,1))-0.05;
plot(t,fid(:,1),'b',t,fid(:,2),'r')
fid is just a pointer corresponding to the opened file and does not have several dimensions, so fid(:,2) will give a matrix dimensions exceeded error. You want to plot the data that came out of the file, KK in your case. Try this:
plot(t,KK(:,1),'b',t,KK(:,2),'r')
I also suspect you might have your indexing the wrong way round, although as your code is not minimal, complete and verifiable, it is difficult to say. You might find you need the following command:
plot(t,KK(1,:),'b',t,KK(2,:),'r')
My data is x,y co-ordinates in multiple files
a=dir('*.mat')
b={a(:).name}
to load the filenames in a cell array
How do I use a loop to sequentially load one column of data from each file into consecutive rows of a new/separate array......?
I've been doing it individually using e.g.
Load(example1.mat)
A(:,1)=AB(:,1)
Load(example2.mat)
A(:,2)=AB(:,1)
Load(example3.mat)
A(:,3)=AB(:,1)
Obviously very primitive and time consuming!!
My Matlab skills are weak so any advice gratefully received
Cheers
Many thanks again, I'm still figuring out how to read the code but I used it like this;
a=dir('*.mat');
b={a(:).name};
test1=zeros(numel(b),1765);
for k=1:numel(b) S=load(b{k});
I then used the following code to create a PCA cluster plot
test1(k,:)=S.AB(:,2); end [wcoeff,score,latent,tsquared,explained] = pca(test1,... 'VariableWeights','variance');
c3 = wcoeff(:,1:3) coefforth = inv(diag(std(test1)))*wcoeff; I = c3'*c3 cscores = zscore(test1)*coefforth;
figure() plot(score(:,1),score(:,2),'+') xlabel('1st Principal Component') ylabel('2nd Principal Component') –
I was using 'gname' to label the points on the cluster plot but found that the point were simply labelled from 1 to the number of rows in the array.....I was going to ask you about this but I found out simply through trial and error if I used 'gname(b)' this labels the points with the .names listed in b.....
However the clusterplot starts to look very busy/messy once I have labelled quite a few points so now I am wondering is is possible to extract the filenames into a list by dragging round or selecting a few points, I think it is possible as I have read a few related topics.....but any tips/advice around gname or labelled/extracting labels from clusterplots would be greatly appreciated. Apologies again for my formatting I'm still getting used to this website!!!
Here is a way to do it. Hopefully I got what you wanted correctly :)
The code is commented but please ask any questions if something is unclear.
a=dir('*.mat');
b={a(:).name};
%// Initialize the output array. Here SomeNumber depends on the size of your data in AB.
A = zeros(numel(b),SomeNumber);
%// Loop through each 'example.mat' file
for k = 1:numel(b)
%// ===========
%// Here you could do either of the following:
1)
%// Create a name to load with sprintf. It does not require a or b.
NameToLoad = sprintf('example%i.mat',k);
%// Load the data
S = load(NameToLoad);
2)
%// Load directly from b:
S = load(b{k});
%// ===========
%// Now S is a structure containing every variable from the exampleX.mat file.
%// You can access the data using dot notation.
%// Store the data into rows of A
A(k,:) = S.AB(:,1);
end
Hope that is what you meant!
I have a large text file with 2 columns where the values are separated by commas. I am trying to create a simple program which allows to plot a graph with the data extracted for every 3 rows consecutively until reaching the end of the file.
The first 9 rows of my file can be seen below:
115,1.2
324,3.4
987,1.2
435,-2.3
234,1.4
278,1.3
768,3.4
345,-1.3
126,3.6
I have been reading that with 'Textread' I can write my data into multiple outputs and then I can use 'plot', to plot the previous generated outputs on a graph. I know that I will need some loop whiles to repeat the process and indicate the end of the file, etc. But I am struggling to find the way to do this:-(.
I have only managed plotting a graph for the first 3 rows of my file (see code below), but I need this process to be repeated until the end of the file.
[Codes,Values]=textread('MyData.txt','%3u %f',3,'delimiter',',','emptyvalue',NAN); %//Reads the first three rows of my file and stores the values in 2 variables
figure
plot(Codes,Values) %//plots a graph with the variables obtained before
saveas(gcf,'Graph.pdf') %//Saves the created graph in a pdf format file.
I would be very grateful if somebody could help me.
I have finally found out a way. I paste here the code that allows me plotting a graph every three lines from my text file.
[Codes,Values]=textread('MyData.txt','%3u %f','delimiter',',','emptyvalue',NAN); %//Reads my text file and stores the values in 2 variables
nrows=1;
conta=1;
contb=3;
contc=1;
contd=3;
nfig=1;
while nrows<=size(Codes,1)
if contb<=size(Codes,1)
Codes1=Codes(conta:contb,1);
Values1=Values(contc:contd,1);
figure
plot(Codes1,Values1) %//plots a graph with the selected rows.
saveas(gcf,strcat('Graph', num2str(nfig),'.pdf')) %//Saves the created graph in a pdf format file.
else
Codes1=Codes(conta:contb,1);
Values1=Values(contc:contd,1);
figure
plot(Codes1,Values1) %//plots a graph with the selected rows.
saveas(gcf,strcat('Graph', num2str(nfig),'.pdf'))
end
nrows=nrows+3;
conta=conta+3;
contb=contb+3;
contc=contc+3;
contd=contd+3;
nfig=nfig+1;
end
You mentioned that it is a large text file, but will it an issue to load the whole text file and then simply sample every third row, for example, as follows:
[Codes, Values] = textread('MyData.txt','%3u %f','delimiter',',','emptyvalue',NAN);
rowstokeep = 1:3:length(Values) % every third line
plot(Codes{rowstokeep}, Values{rowstokeep}); % plot just the rows you wanted