How to insert vector to table?

99 views (last 30 days)
Sierra
Sierra on 3 Sep 2022
Answered: Robert U on 5 Sep 2022
for example, I want to insert vector into NoshellRings. I've tried but error occured.
It said that The value cannot be replaced because the number of elements on the left and right sides is different.
Please let me know how to solve this.
Thanks.
  1 Comment
dpb
dpb on 3 Sep 2022
You must either have exactly the same number of elements in the vector as height() of the table or have an indexing expression for the values to be replaced that contains exactly the same number of locations to replace as the number of elments in the vector. No tolerances allowed.
You've not provided enough information for us to be able to know what either of the vector size is, but the table has 4779 rows so to replace the whole variable the vector has to have 4779 elements, no more, no fewer.
You can replace parts of the whole thing, of course, but then you have to have something like
tVariableName.NoshellRings(1:3)=vector; % if your vector is 3-elements long and you want to replace the first 3
The indexing expression can be explict indices as above or a logical addressing vector, but the count simply has to match.

Sign in to comment.

Answers (1)

Robert U
Robert U on 5 Sep 2022
Hi Sierra,
if you want to save vectors in table elements you can use cell arrays:
testTable = table;
testTable.Sex = ['M';'M';'F';'M';'I'];
testTable.Length = [0.455; 0.350; 0.53; 0.44; 0.33];
testTable.NoShellRings = [4; 7; 9; 10; 7];
testVector = [1 2 3 4 5];
testTable.NoShellRings = arrayfun(@(dIn) {dIn},testTable.NoShellRings);
testTable.NoShellRings{3} = testVector
testTable = 5×3 table
Sex Length NoShellRings ___ ______ _____________ M 0.455 {[ 4]} M 0.35 {[ 7]} F 0.53 {[1 2 3 4 5]} M 0.44 {[ 10]} I 0.33 {[ 7]}
If you want to replace portions of the table with values given in a vector you follow dpb's comment.
testTable = table;
testTable.Sex = ['M';'M';'F';'M';'I'];
testTable.Length = [0.455; 0.350; 0.53; 0.44; 0.33];
testTable.NoShellRings = [4; 7; 9; 10; 7];
testVector = [2 3 4; 6 7 8]; % testVector = [index; value];
testTable.NoShellRings(testVector(1,:)) = testVector(2,:)
testTable = 5×3 table
Sex Length NoShellRings ___ ______ ____________ M 0.455 4 M 0.35 6 F 0.53 7 M 0.44 8 I 0.33 7
Kind regards,
Robert

Community Treasure Hunt

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

Start Hunting!