Matrix sequence manipulation for multiple value assignment

2 ビュー (過去 30 日間)
woahs
woahs 2020 年 1 月 19 日
回答済み: Matt J 2020 年 1 月 19 日
Is there a quick (& simple) way to do the following without a loop? Not even sure why I don't want loops but still figured it'd be nice to know if there was a way. Feels like something obvious I'm just not thinking of..
I have an array and a matrix of indices, e.g.
A = zeros(20, 1);
idxes = [1, 5; ...
10, 13; ...
19, 20];
and I'd like to convert it such that the following is achieved without hardcoding in the indices:
A([1:5, 10:13, 19:20]) = 1;
Equivalent solution with a loop:
for i = 1:size(idxes, 1)
A(idxes(i, 1):idxes(i, 2)) = 1
end

回答 (2 件)

Matt J
Matt J 2020 年 1 月 19 日
編集済み: Matt J 2020 年 1 月 19 日
If the intervals will always be disjoint,
A=zeros(20,1);
n=numel(A);
A(idxes(:,1))=1; A(idxes(:,2)+1)=-1;
A=cumsum(A(1:n))

Matt J
Matt J 2020 年 1 月 19 日
e=1:numel(A);
lidx= any(idxes(:,1)<=e & e<=idxes(:,2),1);
A(lidx)=1;

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

製品


リリース

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by