Cannot create a table variable with a discontiguous index

38 views (last 30 days)
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.

Answers (1)

Vatsal
Vatsal on 13 Jun 2024
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!

Products


Release

R2018b

Community Treasure Hunt

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

Start Hunting!