How to fasten the loop

1 view (last 30 days)
Arun Kumar Singh
Arun Kumar Singh on 22 Sep 2022
Commented: Rik on 22 Sep 2022
for i=1:size(LAT1)-1
disp(i);
if ((Time1(i+1)-Time1(i)==1)&& (strcmp(SAT1(i),SAT1(i+1))) && (strcmp(ST1(i),ST1(i+1))) && (strcmp(COMB1(i),COMB1(i+1))) )
Long{k}(j,1)=Long1(i);
LAT{k}(j,1)=LAT1(i);
STEC{k}(j,1)=STEC1(i);
VTEC{k}(j,1)=VTEC1(i);
ELV{k}(j,1)=ELV1(i);
Time{k}(j,1)=Time1(i);
SAT{k}(j,1)=SAT1(i);
ST{k}(j,1)=ST1(i);
COMB{k}(j,1)=COMB1(i);
j=j+1;
else
k=k+1;
j=1;
end
end
  5 Comments
Torsten
Torsten on 22 Sep 2022
Don't you always forget to put Long1(i), LAT1(i),..., COMB1(i) in the new cell array Long{k+1}(1,1),LAT{k+1}(1,1),...,COMB{k+1}(1,1) if the if-condition is false ?
I mean: Imagine the if-condition is false for all i - then the cell arrays Long, LAT,...,COMB would be empty.
Arun Kumar Singh
Arun Kumar Singh on 22 Sep 2022
No i do not need those values when condition becomes false.

Sign in to comment.

Answers (1)

Torsten
Torsten on 22 Sep 2022
Edited: Torsten on 22 Sep 2022
Maybe there are faster commands than arrayfun for extracting the elements of LONG in cell arrays that correspond to sequences of zeros in the logical i array, but I couldn't find an efficient ad hoc solution for this.
Maybe MATLAB experts can help here.
TIME = [1 2 3 4 5];
SAT1 = ["a","aa","aa","aa","aa"];
ST1 = SAT1;
COMB1 = SAT1;
n = numel(TIME);
I1 = diff(TIME) == 1
I1 = 1×4 logical array
1 1 1 1
I2 = strcmp(SAT1(1:n-1),SAT1(2:n))
I2 = 1×4 logical array
0 1 1 1
I3 = strcmp(ST1(1:n-1),ST1(2:n))
I3 = 1×4 logical array
0 1 1 1
I4 = strcmp(COMB1(1:n-1),COMB1(2:n))
I4 = 1×4 logical array
0 1 1 1
I = (~I1) | (~I2) | (~I3) | (~I4)
I = 1×4 logical array
1 0 0 0
edges = [find(I == 1),n]
edges = 1×2
1 5
LONG1 = [3 10 12 4 8]
LONG1 = 1×5
3 10 12 4 8
LONG = arrayfun(@(i)LONG1(edges(i)+1:edges(i+1)-1),1:numel(edges)-1,'UniformOutput',0)
LONG = 1×1 cell array
{[10 12 4]}
  5 Comments
Torsten
Torsten on 22 Sep 2022
Edited: Torsten on 22 Sep 2022
The contiguous parts of the array LONG1 should be extracted that belong to the contiguous parts where the I array is false.
I = [true false false true true false true]
should extract
LONG{1} = [LONG1(2),LONG1(3)]
LONG{2} = [LONG1(6)]
Rik
Rik on 22 Sep 2022
Perhaps Jan's RunLength function will be helpful to see how to split the contiguous parts efficiently.
Otherwise, ~I should be a good start: you would only have to split that based on the run length of false, for which you could use mat2cell.

Sign in to comment.

Products


Release

R2018b

Community Treasure Hunt

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

Start Hunting!