Cannot create a table variable with a discontiguous index
조회 수: 29 (최근 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에서 Tables에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!