How to read a CSV file into vector matrix of 2 column?
7 views (last 30 days)
Show older comments
I have 2 CSV files which have multiple values. I want to create a vector matrix, which could be of multiple row but 2 column. Index 1 of column 1 will hold first 1000 values from a CSV file1. Similarly, index 1 of column 2 will hold first 1000 values from a CSV file2. And this process will continue until all the data is fetched from both CSV files.
Accepted Answer
Rishi
on 22 Jan 2024
Hi hsnal,
I understand from your query that you want to read data from two CSV files into a vector matrix such that the first column of the matrix contains the data in chunks of 1000 values from the first CSV file, and the second column contains the same from the second CSV file.
Here is a sample code to help you do the same:
csv_file1 = 'file1.csv';
csv_file2 = 'file2.csv';
% Read the data from the CSV files, assuming the data is numeric
data1 = readmatrix(csv_file1);
data2 = readmatrix(csv_file2);
num_chunks = max(ceil(length(data1)/1000), ceil(length(data2)/1000));
vector_matrix = cell(num_chunks, 2);
for i = 1:num_chunks
% Calculate the start and end indices for the current chunk
start_idx = (i - 1) * 1000 + 1;
end_idx = min(i * 1000, length(data1));
% Assign the chunk of 1000 values from each file to the matrix
vector_matrix{i, 1} = data1(start_idx:end_idx);
% Check if the second file has enough data; if not, adjust the end index
end_idx = min(i * 1000, length(data2));
vector_matrix{i, 2} = data2(start_idx:end_idx);
end
You can learn more about 'readmatrix' from the below documentation:
You can also use 'readtable' or 'csvread' to get the data from CSV files, and you can learn more about them here:
Hope this helps!
0 Comments
More Answers (0)
See Also
Categories
Find more on Spreadsheets in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!