How to input first column in data table?

조회 수: 2 (최근 30일)
Kris Sarikanoppakhun
Kris Sarikanoppakhun 2021년 3월 28일
답변: Arjun 2025년 6월 5일
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
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:
  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!

카테고리

Help CenterFile Exchange에서 Get Started with MATLAB에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by