MATLAB Answers

How to read data from a CSV into a column vector

174 views (last 30 days)
waleed khalid
waleed khalid on 5 Nov 2020
Commented: Monika Jaskolka on 5 Nov 2020
I have 25 csv files that I need to grab data from, they are all in the same format with no headers, I would like to grab all of this data, and store it into a column vector. Previous iterations of this program have used fread(filename, size) to read binary files into a column vector and throw them into a calculation script, I would like to keep the script in the same format so I need to read this csv data into a Column Vector.
I also imported them into a table so if there is a way to convert this table into a Column vector that works too, I am not concerned with the loss of efficiency in terms of runtiime.

Answers (1)

Monika Jaskolka
Monika Jaskolka on 5 Nov 2020
Edited: Monika Jaskolka on 5 Nov 2020
>> m = readmatrix('test.csv')
m =
1 2 3 4
5 6 7 8
>> m = m(:)
m =
1
5
2
6
3
7
4
8
For mixed data:
>> m = readtable('test.csv')
m =
2×4 table
Var1 Var2 Var3 Var4
____ ____ _____ ____
1 2 {'a'} 4
5 6 {'b'} 8
>> m = table2cell(m)
m =
2×4 cell array
{[1]} {[2]} {'a'} {[4]}
{[5]} {[6]} {'b'} {[8]}
>> m = m(:)
m =
8×1 cell array
{[1]}
{[5]}
{[2]}
{[6]}
{'a'}
{'b'}
{[4]}
{[8]}
  4 Comments
Monika Jaskolka
Monika Jaskolka on 5 Nov 2020
The data is there, but Matlab has different formats for displaying data in the Command Window. Read more about it here: https://www.mathworks.com/help/matlab/ref/format.html . The default is "format short", which is only 4 decimal places.
So if you want to see more decimals, type in "format long" into your Command Window, and then try to display the matrix again.

Sign in to comment.

Products


Release

R2020b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by