MATLAB: Matlab: optimize code

codeoptimization

Problem: I have the trajectories of 14 users: I have compare the trajectories of every user and for each one, I have calculated the longest common sequence: TrajSimilarity(1,k).aLongestString. Now I want to compare the longest common sequence of the first user with the others, the longest common sequence of the second user with the others and etc.
I have no problems to compare the longest common sequence of two users using this code:
string3=TrajSimilarity(1,3).aLongestString;
string4=TrajSimilarity(1,4).aLongestString;
[D,dist,aLongestString]=LCS(string3,string4);
U=numel(regexp(string3,'(\(\d+\)|\d)'));
V=numel(regexp(string4,'(\(\d+\)|\d)'));
nLCS=numel(regexp(aLongestString,'(\(\d+\)|\d)'));
ratioU=nLCS/U;
ratioV=nLCS/V;
EA = (ratioU + ratioV)/2;
WA = (U*ratioU+V*ratioV)/(U+V);
LCS is a function that calculates the longest common substring between two strings (if can be helpful, I will post a link with it). I have problems to create an optimized code that compare the longest common sequence of the first user with the others, the longest common sequence of the second user with the others and etc. I try this code:
for k=1:14
string3=TrajSimilarity(1,k).aLongestString;
for j=2:14
string4=TrajSimilarity(1,j).aLongestString;
[A(k,j).D,A(k,j).dist,A(k,j).aLongestString]=LCS(string3,string4);
end
end
but it generates error:
Attempted to access L(0,0); index must be a positive integer or
logical.
Error in LCS (line 52)
dist = L(n,m);
Error in Prova1 (line 6)
[A(1,k).D,A(1,k).dist,A(1,k).aLongestString]=LCS(string3,string4);
Can you give me an help? thanks

Best Answer

You definitely need to post your LCS function for more detailed advice because that is the one that contains the error.
Somewhere in there you are attempting to index into an array using a 0-index which is not allowed as Matlab arrays index from 1.
To fix it you need to either change the behaviour of LCS or change your inputs to that function ( string3, string4 ) in such a way that they fit to the expectations of the function in a way that m and n are > 1. That is assuming that m and n are dependent on 'string3' and 'string4' that are passed in (or ar in fact the same variables as those)
i.e. either
  • The function remains as is, but a prerequisite of its usage is that inputs must be > 1
or
  • The inputs stay as they are and the function must change its implementation and thus its expectations so that 0, 0 are valid inputs which give expected outputs.