Error in grain2d/merge (line 45)
A =
sparse(mergeId(:,1),mergeId(:,2),1,length(grains),length(grains));
%split off the recrystallized grains
rgos = 0.02;
grains = grains(grains.GOS<rgos);
CS = grains.CS;
gB = grains.boundary;
gbA = gB('Aus', 'Aus');
%The twinning orientation defined by two parralel directions
twinning = orientation('map', Miller(1, 1, 1, CS), Miller(1, 1, 1, CS), Miller(1, -1, 0, CS), Miller(-1, 1, 0, CS));
%bound for twinning in degrees
bdt=5;
isTwinning = angle(gbA.misorientation, twinning) < bdt*degree;
twinBoundary = gbA(isTwinning);
%merge the grains, update id
[mergedGrains, parentId] = merge(grains, twinBoundary);
%filter off the recrystallized grains in grainsrec
grainsrec = grains(grains.GOS<0.02);
gb=grainsrec.boundary('Aus', 'Aus');
twinning = orientation('map', Miller(1, 1, 1, CS), Miller(1, 1, 1, CS), Miller(1, -1, 0, CS), Miller(-1, 1, 0, CS));
isTwinning = angle(gb.misorientation, twinning) < 1*degree;
%only merge inside recrystallized grains. Therefore only the grain
%boundaries touching only recrystallized grains can be used.
%make a logical matrix to see which gb touch a recrystallized grain
isrecbound = ismember(gb.grainId, grainsRec.id);
%both columns must be one
bothRec=isrecbound(:,1) & isrecbound(:,2);
bothRec = [bothRec, bothRec];
[mergedGrainsrec, parentId] = merge(grains, gb(isTwinning & bothRec), 'calcMeanOrientation');
%Re-find all the grains with GOS<0.02
grains.id = parentId;
mergedgrainsid = grains(grains.GOS<0.02).id;
mergedGrainsrec=mergedGrains(unique(mergedgrainsid));