How to insert vector to table?
82 views (last 30 days)
Show older comments
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1116055/image.png)
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
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.
Answers (1)
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
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,:)
Kind regards,
Robert
0 Comments
See Also
Categories
Find more on Characters and Strings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!