How to input first column in data table?

12 views (last 30 days)
Kris Sarikanoppakhun
Kris Sarikanoppakhun on 28 Mar 2021
Answered: Arjun on 5 Jun 2025
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

Answers (1)

Arjun
Arjun on 5 Jun 2025
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:
  1. Read the data from the file into a matrix using ""readmatrix" function of MATLAB into a variable say "data".
  2. 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".
  3. Combine these new columns with the original data to form a new matrix.
  4. 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!

Categories

Find more on Get Started with MATLAB in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!