How to read in more rows to a cell array from a text file?
Show older comments
Hi all, I needed some help with my code. My code is meant to read in a text file (I've attached a shortened version of what the actual looks like) line by line and put only the numbers into a cell array. (I also wanted to add that I can change the String Category titles in the text document but I cannot change the content under titles.
Stored cell in MATLAB currently looks like this:
0 15 6 2 3
1 3 2 4 0
2 1 6 4 7
3 0 1 4 7
I have two major questions here:
- How can I make this code produce more than just 4 rows? I either need to scan in all of the index under one cell array or create a cell array for each index category, whichever is easier. When I tried to change the 4 in the reshape line it said: "Error using reshape To RESHAPE the number of elements must not change." I got help on this and it was set as a 1x20 matrix (20 elements) and changed to a 5x4 matrix (20 elements) then transposed. I am not sure if there is a better way of doing this especially for a longer textfile.
- What type of tweaks would I need to make to this same code for reading a very similar text file, except with hexadecimal values instead of decimal values? I need the hexidecimal values stored as is, not converted to anything. but the array numbers on the left. I have attached the file "data.txt" to show you what that looks like.
Here is the code so far for the index file:
fid = fopen('index.txt','r');
t = textscan(fid,'%s','delimiter','\t'); %this outputs into just one column
fclose(fid);
% converting strings to numeric types
% changing strings to empty values
t2 = t;
for n = 1:length(t2{1})
t2{1}{n} = str2num(t2{1}{n});
end
% reshapes the 1x20 row matrix into a 5x4 matrix and then transposes it
% Reshape goes down the column first
reshape(t2{1}{2},5,4)';
Accepted Answer
More Answers (0)
Categories
Find more on Data Type Conversion in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!