Cannot create a table variable with a discontiguous index
35 次查看(过去 30 天)
显示 更早的评论
I am trying to create new columns based on a condition as described in the code below:
for j = 1:length(data.var1)
column = 1;
while data.var1(j) > value0
data{column,j} = value1;
column = column + 1;
end
end
I then get this error message:
"Cannot create a table variable with a discontiguous index."
Has anyone come up with a solution for such kind of isses with Matlab tables? I would like to avoid creating the columns at the same time with the table.
0 个评论
回答(1 个)
Vatsal
2024-6-13
Hi,
The error message “Cannot create a table variable with a discontiguous index” in MATLAB usually occurs when there is an attempt to create or modify a table using indices that are not continuous. In this case, you are trying to create new columns in a table based on a condition, which might be causing the indices to be discontiguous.
One possible solution is to preallocate the table with NaN values or some default values before the loop, and then fill in the values based on the condition.
Here is how this can be implemented:
% Pre-allocate columns assuming a max of 3 additional columns for this example
maxColumns = 3;
for i = 1:maxColumns
data.(sprintf('newVar%d', i)) = NaN(height(data), 1); % Initialize with NaN
end
% Define condition values
value0 = 10; % Condition for comparison
value1 = 1; % Value to assign when condition is met
% Iterate over each row and fill new columns based on condition
for j = 1:height(data)
column = 1;
while column <= maxColumns && data.var1(j) > value0
columnName = sprintf('newVar%d', column);
data.(columnName)(j) = value1;
column = column + 1;
end
end
% Display the final table
disp(data);
I hope this helps!
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!