I want to calculate velocity. How do I apply my code to all tables in all cells?
조회 수: 2 (최근 30일)
이전 댓글 표시
Hi,
I have a data set of distances (see "results_distances" attached) and want to calculate the velocity for each row in each table in each cell.
I have the following code:
results_velocity = cell(size(results_distances));
for i = 1:length(results_distances) % iterate over tables in cell array
if ~isempty(results_distances{i}) % check if table is not empty
table_data = results_distances{i};
v_table = table_data; % initialize output table with the same size as input table
% Calculate velocity for each numeric variable (column) in the table
for var = 1:width(table_data)
% Check if the variable is numeric
if isnumeric(table_data{:, var})
% Calculate velocity for each row
for row = 2:size(table_data, 1)
% Subtract previous value from current value and divide by time_interval
v_table{row, var} = (table_data{row, var} - table_data{row-1, var}) / time_interval;
end
end
end
results_velocity{i} = v_table; % store velocity table in output cell array
end
end
However, when I run my code, it seems to only apply the calculation to the first column of tables in the cell array (see "results_velocity"). What am I doing wrong?
Thanks!
댓글 수: 0
채택된 답변
Voss
2024년 6월 11일
load('results_distances.mat')
results_distances is of size 3x12
results_distances
so its length is 12. Recall that length() returns the size of the longest dimension.
length(results_distances)
Iterating from 1 to length(results_distances) is iterating over the first 12 elements of results_distances, which in this case is the first 4 columns (since results_distances has 3 rows).
A same-size example using a numeric matrix:
data = reshape(1:36,3,[])
for i = 1:length(data)
data(i)
end
In order to iterate over all elements of results_distances, use numel instead of length.
time_interval = 1;
results_velocity = cell(size(results_distances));
for i = 1:numel(results_distances) % iterate over tables in cell array
if ~isempty(results_distances{i}) % check if table is not empty
table_data = results_distances{i};
v_table = table_data; % initialize output table with the same size as input table
% Calculate velocity for each numeric variable (column) in the table
for var = 1:width(table_data)
% Check if the variable is numeric
if isnumeric(table_data{:, var})
% Calculate velocity for each row
for row = 2:size(table_data, 1)
% Subtract previous value from current value and divide by time_interval
v_table{row, var} = (table_data{row, var} - table_data{row-1, var}) / time_interval;
end
end
end
results_velocity{i} = v_table; % store velocity table in output cell array
end
end
results_velocity
댓글 수: 5
추가 답변 (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!