Import text file as a matrix in a matlab script [closed] - matlab

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Hi everybody I need to automaticly import certain text files stored in my computer as matrices when I run my script in matlab. How do I do that? Thanks

Although the question shows little effort I am reminded how I started out with no knowledge about input or output whatsoever, it is a quite dense forest of information really.
Basically to read a file you need to:
Open the file
Read the file and assign it to a variable
Close the file
Some functions in MatLab take care of all three steps:
importdata
csvread
dlmread
The functions above are suitable if you have very neat and uniform data. Click the links to read if they are suitable for you. If your data is less uniform, e.g. it contains both numbers and letters, you might want to consider textscan.
Using textscan you must carry out all three steps yourself. First open your file and create a link to your file called a file ID (FID):
FID = fopen('mytextfile.txt')
Next you define a format specifier which describes a single line of data (a row).
formatSpec = '%f %f %f %f %s'
This format specifier represents 4 decimal numbers (floats) followed by a string all seperated by whitespace. For more information on the format specifier see:
http://www.mathworks.nl/help/matlab/ref/textscan.html#inputarg_formatSpec
Now you can read your text file by calling:
C = textscan(FID,formatSpec);
Which stores each column in a cell in C. So the first column is C{1}, the second C{2}, etc.
Finally make sure you close your file by using the file id:
fclose(FID);
Good luck!

Related

How to create a .mat file in Matlab? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have 25 images in a folder and I want to make a .mat file for a road-sign recognition system.
What are the steps for making a .mat file in Matlab?
There may be a better approach for images but here is what I know. If you want to control what goes into the .mat file you can specify what variables in your workspace will be saved using the save command.
% MATLAB R2017a
X = rand(273,273);
Y = rand(273,273);
Z = rand(273,273);
save FileName X Y Z
This creates a file FileName.mat.
You can access the contents using the load command.
clear
load FileName
To save everything in the workspace to a .mat file, use the save command without specifying the variables to save (MATLAB will then save them all).
W = rand(273,273);
save FileName
See the linked documentation for more options and examples.
This requires you to loop through the images in the folder. A direct approach to this is directly loading the images using a loop over [filepath 'image' num2str(j) '.jpg'] with index j where filepath = 'C:\Users\user1\Folder\ImageFolder\'. This uses string concatenation and the num2str command.
If you need to change your current directory within the script,the cd function is useful.
Related Posts:
store multi images in mat file using matlab
how to write to .mat file matlab

How to read data from a .txt file matlab [duplicate]

This question already has answers here:
Read txt file with comma decimal separator in MATLAB [duplicate]
(3 answers)
Closed 3 years ago.
I have this data from a radiation diagram of an antenna in a txt file:
And the text continues. As you see, the integer and decimal part of numbers are separated by commas, instead of points. Moreover, I don't need the first row since they aren't values. I have tried using this code:
file = fread('file.txt')
data = fread(file)
fclose(file)
However, all the data was in a vector, so I tried to visualise a little part of the file, writing data = fread(file, [20,4]). Nevertheless, the data was wrong, here's what I obtained:
I also tried with fscanf function, but I didn't work either. I'd like to open the entire file (without knowing the number of elements previously).
I hope someone can help me. Thank you for your responses.
You can specify the delimiter in many data reading functions so it's not a comma, I find readtable the simplest:
T = readtable( 'file.txt', 'Delimiter', 'tab' );
It looks like your data is tab separated, so use the 'tab' option. You could also use 'space' or any given character.
Comma-formatted decimals can then be converted
c = T.Properties.VariableNames;
for ii = 1:numel(c)
t.(c{ii}) = cellfun( #(x)str2double(strrep(x,',','.')), t.(c{ii}) );
end

How to import a cell array data in MATLAB [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have a set of data in a text file with the format like below. How shall I import the data into MATLAB? Thanks!
{(38.7948,1319,0.8571,119,0),(39.0693,138,0.0897,21,0),(40.7911,63,0.0409,7,0),(103.4512,19,0.0123,5,0),(-26.0424,223,1.0000,28,0)}
{(35.8689,110,0.5093,14,0),(47.7915,41,0.1898,7,0),(59.7489,53,0.2454,7,0),(71.7298,12,0.0556,3,0)}
It's always helpful if you in your question explain what you have tried so far, what the desired result would be or how you inteend to use it. That way the person answering the question don't have to assume a lot of things.
Here I assume that you would like to import each line as a cell with a set of number arrays within.
To get matlab to evalutate the expression correct the parentheses in the brackets need to be replaced
{(1,2),(3,4)}
Error: Expression or statement is incorrect
{[1,2],[3,4]}
ans =
[1x2 double] [1x2 double]
To read the file you could use fopen and then fgetl to get each line. When the result from fgetl isn't a char, the end of the file (EOF) is reached.
% Open file
f = fopen('...path\to\file.txt','r');
C = {};
while true
% Read each line
fStr = fgetl(f);
if ischar(fStr)
% Replace parentheses and evaluate expresission
C{end+1} = eval(regexprep(fStr,{'(',')'},{'[',']'}));
else
% End of file
break
end
end
fclose(f)
Perhaps you need to include some error checks if the data in your file should be formated incorrect. You could also check out other ways to read data, for exmple fread or fscanf

Matlab - fft form ascii [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I want to represent a FFT based on measurements i have saved on a file.
The file is in the format [frequency, amplitude] i.e.
0,00;0,15;
3,91;0,34;
7,81;0,60;
11,72;1,66;
15,63;3,66;
19,53;0,98;
23,44;0,60;
27,34;0,44;
31,25;0,35;
35,16;0,29;
39,06;0,25;
42,97;0,22;
46,88;0,20;
How can i plot those data?
The problem when reading this from a file is that it uses commas instead of points to separate the decimals. To avoid any issues with this, you can read the content of the file as text (leading to one string variable) and replace the commas with points in MATLAB:
fileContent = fileread('input_file.txt');
fileContent = strrep(fileContent ,',','.');
Next you can use the sscanf (string scan) function to extract the floating point values (%f) from the string. With [2,inf] you specify you want the output to have two rows and as many columns as needed.
A = sscanf(fileContent ,'%f;%f;\n',[2,inf]);
You then have an array A with the frequencies in the first row and the corresponding values in the second row. With that you can create any plot you like, e.g.
stem(A(1,:),A(2,:));
title('FFT of a signal');
xlabel('Frequency (Hz)');
ylabel('Amplitude');

Differentiate b/w fscanf and load function in matlab [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
In my matlab program i am reading the data file using fscanf and writing the the code code to read all the values.That makes me write several steps.
How to use Load() function to overcome this ad make it simple.
So the way load works is to load variables from MATLAB binary/ascii files. In order to create said files you'll have to use the save function e.g.
octave:3> T = "Hello"
T = Hello
octave:4> save "-binary" "testfile" T
octave:5> clear
octave:6> T
error: 'T' undefined near line 1 column 1
octave:6> load "-binary" "testfile" T
octave:7> T
T = Hello
octave:8>
Sorry I used octave for the example but it's the same code either way. So if you know your going to be using the same data just save it in a MATLAB's binary format. It should save your self the time of having to use fscanf on it next time your playing around with the data.