I want to calculate velocity. How do I apply my code to all tables in all cells?
1 次查看(过去 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
更多回答(0 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!