How can I vectorize or otherwise speed up this function?

1 回表示 (過去 30 日間)
emm0119
emm0119 2018 年 1 月 17 日
編集済み: Matt J 2018 年 1 月 18 日
I have a function intended to do some initial calculations on an array of test data collected during mechanical fatigue tests run under cyclic load control. It's formatted in 3 columns of time, position and load (each row is a single measurement) The datasets are huge... sometimes 20 million rows or more. Can anyone think of good ways to vectorize these FOR loops? The 2nd loop is especially inefficient, but I'm new to coding with vectors and am having trouble wrapping my head around it.
Thanks for any help or resources you can provide!
function [test,cycleposition] = fatigueimport(test)
% Get length of test and find derivative of load to count cycles
% test data is array with time, position, load in columns
cycle = zeros(length(test),1); %initiate cycle variable
cyclecount=1;
cycle(1)=1;
changeload = diff(test(:,3));
count = length(test)-1
for i=2:count
if and(changeload(i-1)>0,changeload(i)<0)
% tests for point where load changes from increasing
% (positive changeload) to decreasing (negative changeload) and
% increments cyclecount.
cyclecount=cyclecount+1
end
cycle(i)=cyclecount;
i=i+1;
end
test = [test,cycle]; % adds calculated cycle to original array
% Find position of greatest deflection for each cycle
count = max(test(:,4)) % count set to total number of cycles
cycleposition = zeros(count,1); % initiate vector to record deflection values
for i=1:count
cycleposition(i)=min(test(test(:,4)==i,2));
i=i+1;
end
end

採用された回答

Matt J
Matt J 2018 年 1 月 18 日
編集済み: Matt J 2018 年 1 月 18 日
function [test,cycleposition] = fatigueimport(test)
% Get length of test and find derivative of load to count cycles
% test data is array with time, position, load in columns
changeload = diff(test(:,3));
changes=[ 1 ; changeload(1:end-1)>0 & changeload(2:end)<0 ; 0];
cycle=cumsum(changes);
test=[test,cycle];
cycleposition=accumarray(cycle, test(:,2) , [],@min);
  2 件のコメント
emm0119
emm0119 2018 年 1 月 18 日
Thank you so much, this is perfection! What took hours now takes mere seconds.
Matt J
Matt J 2018 年 1 月 18 日
編集済み: Matt J 2018 年 1 月 18 日
You're quite welcome. Welcome to Matlab.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeData Type Identification についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by