Reading multi row comma delimited text file with strings into an nxm matrix
5 views (last 30 days)
Show older comments
I need to read a text file of the following format:
string,string,string
.
.
.
string, string,string
into a matrix of strings that can be referred to through normal A(n,m) notation.
I have tried fscanf, csvread and importdata and readtable but find it impossible to get an nxm matrix that I can reference.
Advice would be great.
2 Comments
Guillaume
on 30 Sep 2016
Edited: Guillaume
on 30 Sep 2016
Prior to R2016b, you could only store strings (actually char matrices) into cell arrays. The syntax for accessing elements of cell arrays is only slightly different:
A{n, m} %get element at row n column m of cell array A
Since R2016b, there's an actual string type that can be stored into matrices and thus accessed with the standard matrix notation. However, it's a matrix of string objects.
s(1,1) = string('some string');
s(2,2) = string('some other string');
Whichever version, you cannot store a char array (the standard 'this is a string') into a matrix since the char array is already a matrix (and you can't have matrices of matrices).
Answers (2)
KSSV
on 30 Sep 2016
clc; clear all ;
fid = fopen('data.txt') ;
S = textscan(fid,'%s','delimiter','\n') ;
fclose(fid) ;
S = S{1} ;
% Remove empty cells
S = S(~cellfun('isempty',S)) ;
% Remove cells with '.'
S(not(cellfun('isempty', strfind(S,'.'))))=[];
2 Comments
KSSV
on 30 Sep 2016
Is the out put of code not in your expecting pattern? If not write those words in the way you want and show it here.
Jan
on 30 Sep 2016
Strings cannot be stored in a "A(m,n)" matrix in Matlab. You can create a cell string instead. Use textscan with the comma as delimiter.
0 Comments
See Also
Categories
Find more on Characters and Strings in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!