Reading multi row comma delimited text file with strings into an nxm matrix

5 views (last 30 days)
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
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).
Paul Nel
Paul Nel on 30 Sep 2016
Thanks for the assistance with which I managed to sort the code out in the following manner:
function [T] = io_test
clc; clear all ;
file_name = 'dependencies_risks.dat';
fd = fopen(file_name);
S = textscan(fd,'%s','delimiter',',') ;
S=S{1};
filesize = size(S);
filesize = filesize(1,1); %for some reason I cannot do size(S)(1,1)
for m= 1:filesize:3
for p = 1:int16(filesize/3)
for n=1:3
T(p,n)=S(3*p+n-3);
end
end
end
t=T(5,3);
fclose(fd);
end

Sign in to comment.

Answers (2)

KSSV
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
Paul Nel
Paul Nel on 30 Sep 2016
Thanks. The answer I was looking for however should convert my (string11, ..., string1n; stringn1...stringnn) file into an matrix such as this
A=[string11, ..., string1n; stringn1...stringnn].
Is this possible?
KSSV
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.

Sign in to comment.


Jan
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.

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!