How to input first column in data table?

2 visualizaciones (últimos 30 días)
Kris Sarikanoppakhun
Kris Sarikanoppakhun el 28 de Mzo. de 2021
Respondida: Arjun el 5 de Jun. de 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

Respuestas (1)

Arjun
Arjun el 5 de Jun. de 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!

Categorías

Más información sobre Get Started with MATLAB en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by