Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save a vector in a .csv file in MATLAB

Tags:

matlab

I have a vector y = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6]' of size 6 x 1.

I want to save this vector in a .csv file, but I want that my .csv file to be like: enter image description here

I wrote this code in MATLAB:

csvwrite('my_file.csv', y)

How can I edit my code in order to get as the file above?

Any help will be very appreciated.

like image 602
Christina Avatar asked Oct 24 '25 19:10

Christina


1 Answers

You can do something like this (assuming y is a column vector)

dlmwrite('my_file.csv',[[1:length(y)]',y])

For example,

y=rand(10,1)
dlmwrite('my_file.csv',[[1:length(y)]',y])

and now the content of my_file.csv looks,

1,0.70605
2,0.031833
3,0.27692
4,0.046171
5,0.097132
6,0.82346
7,0.69483
8,0.3171
9,0.95022
10,0.034446

if your original vector is a row (not a column) looks a bit easier,

y=rand(1,10)
dlmwrite('my_file.csv',[1:length(y);y]')

Also, if you want the header also on the file you can do like this,

y=rand(1,10);
name1 = 'InD';
name2 = 'y';

delimiter = ',';
header = [name1, delimiter, name2];
dlmwrite('my_file.csv',header,'delimiter','');
dlmwrite('my_file.csv',[1:length(y);y]','-append','delimiter',delimiter);

where you can change y for your vector and then define name1 and name2 as you prefer.

EDIT: Just noticed currently MATLAB discourages the use of dlmwrite, in that case this is an alternative also,

y = rand(1,10);
name1 = 'InD';
name2 = 'y';

header = {name1,name2};
output = [header; num2cell([1:length(y);y]')];
writecell(output,'my_file.csv')
like image 183
myradio Avatar answered Oct 26 '25 10:10

myradio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!