Christina
Christina

Reputation: 935

Save a vector in a .csv file in 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.

Upvotes: 4

Views: 3644

Answers (3)

sagunms
sagunms

Reputation: 8515

In Matlab, you can create a helper function to write csv with header like this:

function to_csv(filename, data, header)
    datatable = array2table(data);
    datatable.Properties.VariableNames(1:length(header)) = header;
    writetable(datatable, filename);
end

Usage example:

y = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6]';
InD = (1:length(y))';
to_csv('my_file.csv', [InD, y], ["InD", "y"]);

Upvotes: 1

myradio
myradio

Reputation: 1775

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')

Upvotes: 5

nunohpinheiro
nunohpinheiro

Reputation: 2269

You may create a matrix as following, and save it to the CSV file (below, I used writematrix instead of csvwrite)

y_matrix = [1 0.1; 2 0.2; 3 0.3; 4 0.4; 5 0.5; 6 0.6]
writematrix(y_matrix, 'my_file.csv') 

You can build this matrix with the strategy you desire; e.g., a matrix may be created by joining two vectors. The first vector can be a range with the length of the second vector.

Upvotes: 1

Related Questions