1

I just started using Octave (No money for Matlab :/) and I'm also new to Stack Overflow, so please pardon any error I make with conventions.

Problem: I have a csv of strings like so:

Bob Marley,Kobe Bryant,Michael Jackson,Kevin Hart

I would like to make this into a 1 column matrix (I need it in a matrix so that I can combine it with data that are in other matrices).

My approach: I have tried doing textread, but this gives me a cell array. I tried converting the resulting cell array to a matrix by using cell2mat, but I suspect that I cannot do this because my strings are of varying lengths.

Let me know if any other information is necessary.

0

3 Answers 3

1

You can use char arrays using:

fid = fopen('strings.csv');
A = textscan(fid, '%s', 'delimiter', ',');
B = char(A{:})
[rows, cols] = size(B)

Output is the following:

B =
  Bob Marley
  Kobe Bryant
  Michael Jackson
  Kevin Hart

rows =  4

cols =  15

As you can see, the number of columns of B is the maximum length of all "strings" (Michael Jackson, 15). All other "strings" get whitespaces appended.

Sign up to request clarification or add additional context in comments.

1 Comment

This isn't exactly what I was looking for, but this is pretty neat! Thanks :)
0

Considering you are in the directory where you have a file "strings.csv" with the content you mentioned in the question, your code whould look like this:

fid=fopen('strings.csv');
A=textscan(fid,'%s','delimiter',',');
A=A{1};
A=cellfun(@(x) string(x),A,'uni',0);
B=[A{:}];

4 Comments

I get this error when running your code: warning: the 'string' function is not yet implemented in Octave. Maybe this works for Matlab but not for Octave?
@ShubhamKumar Ok, then I'd like to go back to my original assumption: Does octave even have string matrixes? apparently it has been added to matlab at R2016B and maybe it has not yet been added to Octave. I don't have an installation of Octave so I can't test. This solution works in matlab though.
You might be right, I just resorted to doing cell arrays. Thanks for the help though!
Yep, string objects are Matlab-only. cellstrs (cell arrays containing char vectors in their cells) is the right way to do it in Octave.
0

If your data is that simple, you can do it in a one-liner. Use fileread to slurp all the data in, and then strsplit to separate the elements, and a ' transpose to convert it to a column vector.

x = strsplit(fileread('myfile.txt'), ',')'

If you end up with spaces around the commas in your data, upgrade to regexp.

x = regexp(fileread('myfile.txt'), ' *, *', 'split')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.