Problems with Tables which contain a single row.

8 次查看(过去 30 天)
I have a GUI app working and just doing final testing. Everything is working very well..... except when I encounter a scenario where a table has a single row.
I have replicated the scenario with the following example...
Table3Rows has 3 rows and 3 columns. Table1Row is the same as Table3Rows but only contains the first row.
clc
var1 = ['abc';'def';'ghi'];
var2 = [1;2;3];
var3 = ['x';'y';'z'];
Table3Rows = table(var1,var2,var3) % This table has 3 rows
Table1Row = Table3Rows(1,:) % Same as table above but wth just the first row
TableVar1 =table(Table3Rows.var1) % This works perfectly (ie create a new table with just the first column)
TableVar1Row1 = table(Table1Row.var1) % This is identical except Table1Row has only 1 row but causes an error
The last 2 instructions are identical. The last instruction creates an error.
In a real world scenario, I cannot control how many rows may be in the table. It may be empty, 1, 10,1000's.
Any hints on how I can cater for the single row (within a table) scenario.

采纳的回答

Matt O'Brien
Matt O'Brien 2022-8-28
What a super quick response.... really appreciated.
I have refined your version as follows. I prefer to use the column variable names .... as the tables in use have 15-20 columns and the design is still evolving... Too difficult to debug if one of the columns moves relative to the others...
clc
var1 = ['abc';'def';'ghi'];
var2 = [1;2;3];
var3 = ['x';'y';'z'];
Table3Rows = table(var1,var2,var3) % This table has 3 rows
Table1Row = Table3Rows(1,:) % Same as table above but wth just the first row
% TableVar1 = Table3Rows(:, 1) % Extract only the first column into a new table.
% TableVar1Row1 = Table1Row(:, 1) % Extract only the first column into a new table.
TableVar1 = Table3Rows(:, "var1") % Extract only the first column into a new table.
TableVar1Row1 = Table1Row(:, "var1") % Extract only the first column into a new table.

更多回答(1 个)

Image Analyst
Image Analyst 2022-8-28
Don't use table(). Try it using indexing:
var1 = ['abc';'def';'ghi'];
var2 = [1;2;3];
var3 = ['x';'y';'z'];
Table3Rows = table(var1,var2,var3) % This table has 3 rows
Table1Row = Table3Rows(1,:) % Same as table above but wth just the first row
TableVar1 = Table3Rows(:, 1) % Extract only the first column into a new table.
TableVar1Row1 = Table1Row(:, 1) % Extract only the first column into a new table.
  1 个评论
Matt O'Brien
Matt O'Brien 2022-8-28
To. Image Analyst.
Super, quick, working solution. I presume some people will prefer the index value method.
I prefer to use the column variable name to identify the columns, to make my code more readable and less likely to mix up index numbers.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Testing Frameworks 的更多信息

产品


版本

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by