MATLAB : Reading Data from a Updating file - matlab

I wrote a code for reading from a .txt file and putting it in the code below. When used without a loop or when looped once, it works fine. But I loop infinitely or over a certain constraint,it gives the error
Error using dlmread (line 147)
Empty format character vector is not supported at the end of a file.
My .txt contains 3 values separated by spaces.
How do I debug this error?
while 1
A =dlmread("Data.txt");
c130(30,10,0,...
'color','red',...
'pitch',A(1),...
'yaw',A(2),...
'roll',A(3),...
'scale',2)
view([42 8])
axis tight
end

Related

Reading numeric data from CSV file Matlab for specific columns?

I have two .csv files which I am trying to read into Matlab as numeric matrices. Call it list_a, simply has two columns of ID numbers and corresponding values (appr. 50000 lines) with a ',' delimiter. list_b has 6 columns with a ';' delimiter. I am only interested in the first two columns containing containing numbers; the other columns contain text that I don't care about.
I initially tried using the readtable function in Matlab but noticed that these values aren't stored as numeric values, which is a requirement I have. I couldn't figure out how to cast these as integers after reading them either.
For list_a I have used the dlmread function, which I believes reads the file as numeric values.
For list_b I have tried using the dlmread function in which row and column offsets can be specified (https://www.mathworks.com/help/matlab/ref/dlmread.html#d117e329603) - the problem here is however, that the length of the file could change in the future, so I'm not sure what to enter for the row offsets.
I'm also not sure I understand how this function works, considering I tried testing it for the first 1000 rows as follows:
csv_matrix = dlmread(csv_fullpath,';',[1 1 1000 2]);
and subsequently got the following error message - even though "field number 3" shouldn't even be included in the first place:
Error using dlmread (line 147)
Mismatch between file and format character vector.
Trouble reading 'Numeric' field from file (row number 1, field number 3) ==>
RandomTextInFile\n Error in Damage_List_Reader (line 15)
csv_matrix = dlmread(csv_fullpath,';',[1 1 1000 3]);
I get the impression that I'm making this problem a lot harder than it needs to be so if there's an all around better way to do this, I'm all ears.. Thanks!
I would suggest using fopen in combination with textscan (e.g. for list_a) like this:
file = fopen('list_a.csv');
out = textscan(file, '%d%f', 'delimiter', ',');
ID = out{1};
Vals = out{2};
'%d%f' specifies the FormatSpec, so the way how the data is formatted in file. With this, you can capture any data from a csv file (and also omit data). I recommend reading the textscan Matlab doc for further formatting issues.
P.S.: I think you can put and "end" (without the quotations) instead of one of the row offset values if the number of rows/cols isn't fixed.

Matlab error while creating csv file from image set using imread and csvwrite

I want to convert a set of images into a csv file. I was working with Matlab and I need each row corresponding to one image. I tried to do it with the following code
I=imread(c{n});
csvwrite('C:\Users\HP\Desktop\test.csv',I(:).','-append'); % c{n} contains the name of image files to be taken
but I am getting the following error
Error using dlmwrite (line 112)
Invalid attribute tag: ,.
Error in csvwrite (line 42)
dlmwrite(filename, m, ',', r, c);
Error in Untitled (line 7)
csvwrite('C:\Users\HP\Desktop\test.csv',I(:).','-append');
but if I try to do it without the '-append' there is no error.
How to change the code such that it takes all the images at once and produces a csv file with the single execution of the code.
csvwrite is meant for writing comma separated values, so adding that ',' is wrong. Then you have put a dot('.') after I(:), which is also wrong. I think you should better use dlmwrite if you want to append the files. It would go like dlmwrite('C:\Users\HP\Desktop\test.csv',I(:)','-append') (since you want each image as one row, you need to transpose the array).
For using this on all images, start by reading all the images into a cell array & then you use cellfun(#(x) dlmwrite('C:\Users\HP\Desktop\test.csv',x(:)','-append'),a). Or for a much simpler version just run the lines in your code inside a for loop.

Load matrix from .dat file Matlab (except remove first 8 rows)

To simplify my problem, I am trying to load a file named data.dat.
I however do not know how to import a only a specific number of rows. For example:
Blue Red Green
1 2 4
1 3 4
0.1 2.2 3
.
.
.
How do I go about only importing rows from 0.1 and below. I do not want the first 2 rows nor the headers.
I know this is a fairly simple problem but I keep running into the following error:
Error using textscan. Invalid file identifier. Use fopen to generate a valid file identifier.
fid = fopen('data.dat', 'r');
mat = textscan(fid, '%f', 'HeaderLines', 1);
fclose(fid);
I thought that this works by removing the first row but I am clearly mistaken.
You can use dlmread command like single line of the code below (I'm assuming that your file located at the current working directory, otherwise use the correct path):
mat = dlmread('data.dat','',4,0);
Note: You don't need to open/close the file.

Convert matlab fig into csv, txt or ascii

I have the m-file on generating all the graphs in .fig I need with a for loop, but I don't know how to extract the array data to csv, txt or ascii format (16-bit).
imagesc(x,y,C); %C is the data I want to extract
%m and n are variables created inside the for loop
I have tried dlmwrite and save, but I failed and could not fix the problem.
So I want to convert fig into csv, txt or ascii format instead.
filename_B=strcat(MM,'_profile'); %MM is a variable created inside the for loop
dlmwrite(filename_B.txt,squeeze(Data_time(:,m,n,:)),''); %Data_time is C
save(filename_B, squeeze(Data_time(:,m,n,:)),'-ascii','-double');
I have also tried csvwrite
filename_B=strcat(MM,'_profile');
csvwrite(filename_B.txt, squeeze(Data_time(:,m,n,:)));
but there is an error message, "??? Attempt to reference field of non-structure array."
It would be better if I could just extract the data directly to the desirable format without first producing fig then convert.
For confidential issue, I can't provide the whole script, but I will try my best to explain my problem.
Many thanks!

Error "Index exceeds matrix dimensions." in MatLab using importdata with a text file

I'm trying to import data using importdata and when I try to parse the returned data to create a matrix I get, "Index exceeds matrix dimensions". Below is my code...
traindata = importdata('textfile.txt');
%[A,delimiterOut,headerlinesOut] = importdata('textfile.txts');
disp(traindata); %everytime I run this code traindata increments by 1
X = traindata(' ',1:8); %this is where the error occurs, delimiter is 3 spaces
Y = traindata(' ',9);
Below is the format of the data in textfile.txt...
,,,5.4,,,0.0,,,0.0,,,1.6,,,2.5,,,1.0,,,6.7,,,2.8,,,6.1
,,,4.2,,,1.1,,,3.6,,,3.9,,,1.8,,,9.3,,,3.3,,,2.4,,,7.6
The data is delimited by spaces (I used commas to try and show the spaces between the data) and a newline at the end of each line. I've open textfile.txt in word and verified by viewing the hidden formatting characters. I've tried the code...
[A,delimiterOut,headerlinesOut] = importdata(inputfile);
to try to verify the delimiter used and I get the error, "Too many output arguments." As you can see I'm trying to create two matrices (X,Y) from the imported data. I've seen this specific error on stackoverflow but nothing regarding importdata. I've also tried dlmread and have not had luck. Thanks in advance for any help.
Tried the suggestion of importing the data using file->import data but I receive the error..
Error using importdata
Too many output arguments.
"Error in uiimport/runImportdata (line 433)
[datastruct, OTextDelimiter, OHeaderLines] = ...
Error in uiimport/gatherFilePreviewData (line 376)
[datastruct, textDelimiter, headerLines]= runImportdata(fileAbsolutePath, type);
Error in uiimport (line 194)
[ctorPreviewText, ctorHeaderLines, ctorDelim] = ..."
I'm starting to wondering if it's some sort of application bug. Here are some specifics..
"R2012a (7.0.14.739) 64 bit (Win64)". The encoding of the text file is utf-8. Thanks again for the help!
Looks like the array returned from importdata is a 1 element array.
train = importdata('textfile.txt');
fprintf('1st element in array %d\n', traindata(1)); % prints a number a number that increase each time I run this function ie 1,2,3,4...
fprintf('2nd element in array %d\n', traindata(2)); % produces error, "Index exceeds matrix dimensions"
I often find it useful to use matlab's built in GUI for importing a data file, which can help to visualised how the data will be imported. There is an option in here to produce the code required to replicate the options that were selected during the import which will allow you to work out how to dynamically import the data.
Just go to:
File >>> Import Data...