I have a function that takes one vector as its input, uses another function to create a derivative vector from the input, and then compares the two vectors to produce its output vector. I currently have it working with a for loop as follows:
function [parentIndexVec] = computeParentIndex(nameVec)
parentNameVec = computeParentName(nameVec);
for i=1:length(parentNameVec)
parentIndexVec(i) = find(strcmp(nameVec, parentNameVec{i}));
end
end
The computeParentName
function essentially returns a copy of nameVec
with its last letter removed. The cell arrays preceding the loop then appear as follows:
nameVec = '' 'a' 'b' 'aa' 'ab' 'ba' 'aba' 'abb'
parentNameVec = '' '' '' 'a' 'a' 'b' 'ab' 'ab'
The goal of this function is to find the indices of where each element in parentNameVec
appears in nameVec
, and its output is thus as follows:
parentIndexVec = 1 1 1 2 2 3 5 5
I attempted to make a cellfun
to accomplish this, but was unable to get it to operate as the two vectors must be compared at each point.
My questions are as follows:
- Is there a way to do this by eliminating the loops?
- Is it truly faster to have matrix operations rather than loops in most cases?
- If so, does
cellfun
compare in speed to pure matrix operations or would it be as slow as a loop?
Thanks for any assistance!