Changing elements of vector with matrix

1 回表示 (過去 30 日間)
Michael Clausen
Michael Clausen 2020 年 6 月 24 日
コメント済み: Michael Clausen 2020 年 6 月 24 日
I have a question regarding a simple operation that I cant find an answer to. Hope that someone can help me.
I have a vector a:
a = zeros(1,10)
and a matrix b:
b = [1, 3; 6, 8]
I want to change elements of a into ones in accordance with the segments indicated by matrix b:
The result should be
1 1 1 0 0 1 1 1 0 0
When I try:
a(b(:,1):b(:,2)) = 1
I get
1 1 1 0 0 0 0 0 0 0
Best regards,
Michael

採用された回答

Stephen23
Stephen23 2020 年 6 月 24 日
編集済み: Stephen23 2020 年 6 月 24 日
No loop required:
>> v = 1:numel(a);
>> x = any(v>=b(:,1) & v<=b(:,2), 1); % requires MATLAB >=R2016b
>> a(x) = 1
a =
1 1 1 0 0 1 1 1 0 0
For earlier versions replace the logical comparisons with bsxfun.
Or just use one simple loop:
>> for k = 1:size(b,1), a(b(k,1):b(k,2)) = 1; end
>> a
a =
1 1 1 0 0 1 1 1 0 0
  3 件のコメント
Stephen23
Stephen23 2020 年 6 月 24 日
"I was hoping to do the manuvre without a loop"
See my edited answer.
Michael Clausen
Michael Clausen 2020 年 6 月 24 日
Thanks :-)

サインインしてコメントする。

その他の回答 (2 件)

Ashish Azad
Ashish Azad 2020 年 6 月 24 日
編集済み: Ashish Azad 2020 年 6 月 24 日
The syntax you are using is very ambiguous and will never work
Try
for i=1:length(b)
a(b(i,1):b(i,2))=1;
end
Let me know if this work
  2 件のコメント
Stephen23
Stephen23 2020 年 6 月 24 日
編集済み: Stephen23 2020 年 6 月 24 日
Do NOT use length for this code:
for i=1:length(b)
Consider what would happen if b only has one row.
The only robust solution is to use size and specify the dimension.
Ashish Azad
Ashish Azad 2020 年 6 月 24 日
Yeah truly said Stephen, size would be robust option

サインインしてコメントする。


Alan Stevens
Alan Stevens 2020 年 6 月 24 日
One way as follows:
a =
0 0 0 0 0 0 0 0 0 0
>> b
b =
1 3
6 8
>> a([b(1,1):b(1,2) b(2,1):b(2,2)]) = 1
a =
1 1 1 0 0 1 1 1 0 0

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by