How to insert vector to table?

조회 수: 98 (최근 30일)
Sierra
Sierra 2022년 9월 3일
답변: Robert U 2022년 9월 5일
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
dpb
dpb 2022년 9월 3일
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.

댓글을 달려면 로그인하십시오.

답변 (1개)

Robert U
Robert U 2022년 9월 5일
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

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by