MATLAB Answers

How to create a matrix from csv files?

4 views (last 30 days)
Nicolas Sylvestre
Nicolas Sylvestre on 28 Nov 2019
Answered: Andrei Bobrov on 29 Nov 2019
Hi,
I have a text matrix with my file names called log_files
log_files = ['file1.csv';'file2.csv';'file3.csv';'file1.csv';'file1.csv';'file4.csv']
I also have a matrix with the data of each csv files, called datafiles
datafiles = [1 1 1;2 2 2;3 3 3;4 4 4]
Where [1 1 1] is the data in file1.csv, [2 2 2] is the data in file2.csv, [3 3 3] is the data in file3.csv and [4 4 4] is the data in file4.csv
What I want, is a matrix called log_data that would look like this (according to log_files)
log_data= [1 1 1;2 2 2;3 3 3;1 1 1;1 1 1;4 4 4]
Thank you for the help you will provide.

  1 Comment

Rik
Rik on 29 Nov 2019
Do you really have a char array? Or is it actually a cell array with the file names?
You can use a loop to read each file and store them in a matrix. What have you tried so far?

Sign in to comment.

Answers (2)

Walter Roberson
Walter Roberson on 29 Nov 2019
filenames = {'file1.csv', 'file2.csv', 'file3.csv', 'file4.csv'};
log_files = {'file1.csv';'file2.csv';'file3.csv';'file1.csv';'file1.csv';'file4.csv'};
[~, idx] = ismember(log_files, filenames);
log_data = datafiles(idx,:);

  0 Comments

Sign in to comment.


Andrei Bobrov
Andrei Bobrov on 29 Nov 2019
[~,~,i] = unique(log_files);
log_data = datafiles(i,:);

  0 Comments

Sign in to comment.

Sign in to answer this question.