"Unable to perform assignment because the left and right sides have a different number of elements error" using find command

1 visualizzazione (ultimi 30 giorni)
reference=[1 2 3 4 5 6 8 9 10];
target=[1 2 3 4 6 7 8 9 10];
for i=1:9
index(i)=find(reference(i)==target);
end
Here, after i reaches 4, "unable to perform assignment" error occurs because:
find(reference(5)==target) = 0×1 empty double column vector
. How I can create the index array without encountering this error such as:
index=[1 2 3 4 0 0 1 1 1]; %or
index=[1 2 3 4 NaN NaN 1 1 1];
My matlab version is R2019a.

Risposta accettata

Walter Roberson
Walter Roberson il 23 Set 2021
reference=[1 2 3 4 5 6 8 9 10];
target=[1 2 3 4 6 7 8 9 10 3 8];
index = [];
complete_reference = [];
for i=1:9
thisref = reference(i);
match = find(thisref==target);
if isempty(match)
complete_reference(end+1) = thisref;
index(end+1) = NaN;
else
index = [index, match];
complete_reference = [complete_reference, repmat(thisref, 1, numel(match))];
end
end
complete_reference
complete_reference = 1×11
1 2 3 3 4 5 6 8 8 9 10
index
index = 1×11
1 2 3 10 4 NaN 5 7 11 8 9
We must assume that there could be multiple matches between the target and the reference, not just none or exactly 1, so we created an extended reference that repeats the reference number as often as needed to put in all of the matches.

Più risposte (0)

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by