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

1 回表示 (過去 30 日間)
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.

採用された回答

Walter Roberson
Walter Roberson 2021 年 9 月 23 日
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.

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by