How to insert a row in a matrix

56 vues (au cours des 30 derniers jours)
Raheema Syed
Raheema Syed le 19 Fév 2019
Commenté : John le 21 Déc 2022
I have a 31x 12 matrix, after the 11th row i want to insert a row matrix with zero values. so that i can make it 32x12 matrix.
how am i supposed to insert a zero row matrix after 11th row

Réponse acceptée

Adam Danz
Adam Danz le 19 Fév 2019
Modifié(e) : Adam Danz le 25 Fév 2019
Here's an example.
data = rand(31,12); % your original matrix
newRow = zeros(1,size(data,2)); % row of 0s
newData = [data(1:11, :); newRow; data(12:end, :)] % your updated matrix
  1 commentaire
John
John le 21 Déc 2022
This also works:
% Adding text to the middle of a text file.
file = ["I have a 31x 12 matrix,";" after the 11th row i want to insert ";...
"a row matrix with zero values.";"so that i can make it 32x12 matrix."];
Insert_string = "The quick brow fox";
i = 2;
file = [file(1:i,:); Insert_string; file(i+1:end, :)];
file =
5×1 string array
"I have a 31x 12 matrix,"
" after the 11th row i want to insert "
"The quick brow fox"
"a row matrix with zero values."
"so that i can make it 32x12 matrix."

Connectez-vous pour commenter.

Plus de réponses (1)

Jorge Fonseca
Jorge Fonseca le 22 Juin 2022
Hi Adam,
What if the "data" table as variable names? I have a table that I imported from Excel with variable names and i can add a row of zeros.
Regards
Jorge
  2 commentaires
Adam Danz
Adam Danz le 22 Juin 2022
Here's a demo that starts with the imported table. For simplicity, I used numeric data for all table variables. When you're appending rows to a table, the variable types within each column may not change.
T = array2table(randi(9,5,4))
T = 5×4 table
Var1 Var2 Var3 Var4 ____ ____ ____ ____ 9 9 5 4 4 1 1 2 2 5 3 3 3 6 5 4 2 2 8 8
Option 1: Add a row of zeros using vertical concatination
% Convert the rows of 0s to a table using the same variable names as
% original table.
T0 = array2table(zeros(1,width(T)),'VariableNames', T.Properties.VariableNames)
T0 = 1×4 table
Var1 Var2 Var3 Var4 ____ ____ ____ ____ 0 0 0 0
% Concatinate tables
T2 = [T; T0]
T2 = 6×4 table
Var1 Var2 Var3 Var4 ____ ____ ____ ____ 9 9 5 4 4 1 1 2 2 5 3 3 3 6 5 4 2 2 8 8 0 0 0 0
Option 2: Add a row of zeros using indexing
T{end+1,:} = zeros(1,width(T))
T = 6×4 table
Var1 Var2 Var3 Var4 ____ ____ ____ ____ 9 9 5 4 4 1 1 2 2 5 3 3 3 6 5 4 2 2 8 8 0 0 0 0
Now you can move the row(s) of added data to some other row(s) in the table. This example moves the row of 0s to row 3 of the table.
T = T([1,2,end,3:end-1],:)
T = 6×4 table
Var1 Var2 Var3 Var4 ____ ____ ____ ____ 9 9 5 4 4 1 1 2 0 0 0 0 2 5 3 3 3 6 5 4 2 2 8 8
Jorge Fonseca
Jorge Fonseca le 26 Juin 2022
Both solutions solve the problem.
Thank you!

Connectez-vous pour commenter.

Catégories

En savoir plus sur Tables dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by