Open a text file, scan it and plot it in MATLAB - matlab

I am trying to open a text file in MATLAB and plot it in a graph. The following is my code:
%% Get the data
[filename, pathname] = uigetfile('*txt', 'Pick text file');
x=filename(:,1);
y=filename(:,2);
plot(x,y);
But each time I run it, I get following error:
Error using plot
Invalid first data argument.
Error in readtxtfile (line 5)
plot(x,y);
The text file that I imported has 2 rows. I am planning to plot the first row with the second say plot (row 1, row 2) in MATLAB.

You have the name of the file stored in filename combined with the path to the directory where the file is stored in pathname but you actually haven't read any of the contents. To do that, the easiest thing would be to use dlmread. I'm assuming your text file is properly formatted to have two rows of data as you stated. If this is the case, you need to change the way you're indexing into your data. You have it indexing entire columns instead of rows so you need to flip the indexing in your code. Also, you need a call to dlmread, then access the columns of the resulting matrix:
%% Get the data
[filename, pathname] = uigetfile('*txt', 'Pick text file');
data = dlmread(fullfile(pathname, filename));
x=data(1,:);
y=data(2,:);
plot(x,y);
Notice that I made the full path to your file to use fullfile because using uigetfile allows you to read in a file from anywhere on your computer so we make sure that we capture the full path to your file. Again to reiterate, pathname is the directory of where the file is contained and filename is the name of the file contained in the directory.

Related

Efficiency loading a file into Matlab

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

How can I write a csv line by line?

I am performing a simulation many many times, and would like to store the result in a csv file.
I could just save the results in an array and write the array to a csv, but the array would be very large and a big strain on my system.
I was thinking it could be easier to simulate, save the result of one simulation in a csv, complete a new simulation, and then store the new result in the second line of the csv.
How can I write csv lines one by one in matlab?
Easy, use: dlmwrite(filename,M,'-append')
For example:
simulation_results = [1,2,3,4]
dlmwrite('C:\<Your Directory Path>\simulaton_results.csv', simulation_results, '-append');
This will append the simulation_results matrix to the end of the file you specify. The default delimiter is a comma ... perfect for writing csv files.
Try fprintf
%save to file
%save using fprintf function
fid_out = fopen('file_out.csv','w'); %open file and create fid
%save tab-separated column headers
%define column format and names and save to file
fprintf(fid_out,'%s\t%s\t%s\t%s\n','a_name','b_name','c_name','d_name');
%save tab-separated columns of data
for i = 1:size(data,1) %loop trough each line of each data variable and save to file line by line
%define column format and date to be saved.
%use () for numeric data, and {} for strings
fprintf(fid_out,'%s\t%s\t%d\t%.5f\n',a{i},b{i},c(i),d(i));
end
fclose(fid_out); %close file
%NOTE: fprintf cannot save structured data

Writing to text file in matlab

I want to do some operations on images and write some data into a txt file.Here is what I am doing for one image-
clc;
image=imread('im.png');
.... %do some operations
....
....
fileID=fopen('first.txt','w');
.... %write onto the txt file
....
fclose(fileID);
But I want to do this for many images.I have stored all the images in a folder.Also, I want to continue writing in the same text file immediately after where I left off for the previous image.How can I modify my code to achieve this?
Well that's pretty simple. Use a loop and loop over all of your images, do your processing on it, then append to the text file. What'll be easier is that you just open the file for your text ONCE, write for as many times as you have images, then finally close it.
Something like this:
folder = ...; %// Place folder here - Example: folder = fullfile('D:', 'images');
fileID=fopen('first.txt','w'); %// Open up the file for writing
f = dir(fullfile(folder, '*.png')); %// look for all PNG files in this folder
for idx = 1 : numel(f)
filename = fullfile(folder, f(idx).name); %// Get the file name
im = imread(filename); %// Read the image in
.... %do some operations
....
....
.... %write onto the txt file
....
fprintf(fileID, '\n\n'); %// Put two carriage returns to make way for next file
end
fclose(fileID);
The function dir scans for all files that match a particular expression. In your case, you want to find all PNG files in a particular folder of your choosing. I assume that this is stored in the variable folder. We then open up the file first before we do anything to the images, then loop over each of the found images with dir. Take note that when you use dir, it only finds the relative paths to the files (i.e. just the names themselves). If you want to locate where the actual images are, you need the absolute paths, which is why we use fullfile.
So, for each PNG image that's in the folder, load it in, do your processing on it, write to your file and I make sure that I put in two carriage returns to separate each result. You repeat this for each PNG image until you exhaust all of them from the folder. Once you're done, you close the text file.
Minor note
image is an actual function in MATLAB that visualizes a matrix of values as an image with a specified colour map. You should probably rename this variable to something else so you don't overshadow the function in case other scripts / functions you write use this function.

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

MATLAB query about writing results to text file

I have a question about outputting some results to a text file in MATLAB. Essentially I have read in data from 50000 files (numbered sequentially from 1 to 50000) and I have plotted it. Only those files which meet a certain condition are plotted. I now want to add some code which will allow me to write text to a data file. The specific text I want to write is the file numbers (from 1 to 50000) which meet the certain condtions and have been plotted.
When I try and do this the plots work fine but the text file only contains the last file number. For example if the last file number to fulfil the conditions to be plotted is 50000, then the text file only contains 50000. I am unsure how to change the code - any help/advice/tips would be appreciated.
start_sim=1;
end_sim=50000;
h = zeros (1,10000);
for i=start_sim:end_sim
a=int2str(i);
File =strcat('result_', 'simulation', '_', a, 'I_byCal_totale.out');
est_tot=importdata(File, '\t', 1);
cal_tot=est_tot.data;
magnitude=1;
t1=cal_tot(:,1)+1750;
model=cal_tot(:,3)+cal_tot(:,5);
if (model(211)>=25)
if (model(211)<=150)
h(a)=plot(t1,model);
xlim([1910 1970]);
ylim([0 500]);
hold all
clickableLegend(h(a),a,'Location','BestOutside')
%Generate OutputFile
fid = fopen('Modeloutputs.in','w+');
%Generate some text to write in the file (e.g. the simulation number)
% Print the text in the file
fprintf(fid,h(a),'\t','\n');
%close the file
fclose(fid);
end
fid = fopen('Modeloutputs.in','a+');
should do your job. Your initial attempt using 'w+' will
Delete the contents of an existing
file or create new file, and open it
for reading and writing.
as the documentation says. Another option is to move fopen & fclose outside of your loop which I would favor.