0

Now that string array is a thing since R2016b, is there a native function that export a string array to csv file and vice versa?

A function that fills the same role of csvread and csvwrite for numeric arrays in the old days but for string arrays. And to relax the requirement, say the string array contains columns of pure strings and columns of pure doubles. Stock prices with time stamp strings would be an example.

Native = not looping with fprintf. But if you are certain Matlab hasn't included any such functions yet, feel free to answer with the best approach thusfar without any restrictions.


Without any native function, pre-R2013a, looping with fprintf is the only way I can think of. And it was awful. Given past reputation of inefficiency, I still don't trust looping in Matlab.

Post-R2016b, one can convert a string array to cell array with num2cell and then to table with cell2table. Table can be written to csv file with writetable. This is actually fast, as writetable is fast. Only num2cell slows down the whole process a little. However, formatting is impossible along the way.

Post-R2019a, cell2table can be skipped with writecell, which is nice but the time consuming (slightly) step is num2cell and formatting should still be impossible. (I don't have R2019a to test it.)

Is there a better way or is it another one of those basic things left to be desired about Matlab?

1 Answer 1

1

writematix and readmatrix are the functions to do that since R2019a.

%If S1 is a string array that you want to `foobar.csv` then:
writematrix(S1,'foobar.csv');

%To read this csv file back into MATLAB as the same string array, use:
S2 = readmatrix('foobar.csv','OutputType','string');

%Verifying the result:
isequal(S1,S2)
ans =
  logical
   1

Loops have been significantly improved since R2015b. Not all loops are slow and not all vectorised versions are faster. The correct approach is to timeit when in doubt.

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

2 Comments

Thanks. Do you know of any pre-R2019a methods?
Pre-R2019a methods are already mentioned by you. Any other variant of those will be more or less similar

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.