How to input first column in data table?
显示 更早的评论
hello everyone i very new in matlab, so i want to know that how to insert first column in my data.
My data is a file that in clude 861*2 number for my result it be like
0 0
0 1
0 2
0 3
so i want to include two column in front like this below
Grid 1 0 0
Grid 2 0 1
Grid 3 0 2
Grid 4 0 3
thank you
回答(1 个)
Arjun
2025-6-5
Assuming your data is stored in a file named "data.csv" and it is located in your current MATLAB path, you can follow these steps:
- Read the data from the file into a matrix using ""readmatrix" function of MATLAB into a variable say "data".
- Create two new columns. The first column, named "label", should contain the string "Grid" repeated for each row of "data" and the second column should contain serial numbers from 1 to the number of rows in "data".
- Combine these new columns with the original data to form a new matrix.
- Write the updated matrix back to disk using "writematrix" function of MATLAB.
Kindly refer to the code section below:
% Read the original data from 'data.csv'
data = readmatrix('data.csv');
% Create the new columns
labels = repmat("Grid", size(data,1), 1); % Column of "Grid"
indices = (1:size(data,1))'; % Column of row numbers
% Combine all columns
data = [labels, num2cell(indices), num2cell(data)];
% Write to a new CSV file
writematrix(data, 'data.csv');
You can read more about "readmatrix" and "writematrix" function of MATLAB by using the following commands in the command window of MATLAB:
- doc readmatrix
- doc writematrix
I hope this helps!
类别
在 帮助中心 和 File Exchange 中查找有关 Get Started with MATLAB 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!