Faster way of replacing multiple rows with same vector without using a loop?
21 ビュー (過去 30 日間)
古いコメントを表示
Hi,
I have a matrix a (see below). I would like to replace the 1st and 3rd row with the same row vector [255 100 0].
a =
245 255 255
254 252 255
251 250 239
Initially I created an index variable 'idx'
idx = [1;3]; % indexing row number for vector replacement
However
a(idx,:) = [255 100 0 ];
would give error messages
'Unable to perform assignment because the size of the left side is 2-by-3 and the size of the right side is 1-by-3'.
How to do it correctly without do it in a loop?
0 件のコメント
採用された回答
Stephen23
2019 年 1 月 29 日
編集済み: Stephen23
2019 年 1 月 29 日
Here are your two main choices for avoiding a loop.
Method one: match the elements. You need to make the LHS and the RHS have the same number of elements (and they need to be in the required order). Here is one easy way to do that:
a(idx,:) = repmat([255,100,0],numel(idx),1)
Tested:
>> idx = [1;3];
>> vec = [255,100,0];
>> a = [245,255,255;254,252,255;251,250,239]
a =
245 255 255
254 252 255
251 250 239
>> a(idx,:) = repmat(vec,numel(idx),1)
a =
255 100 0
254 252 255
255 100 0
Method two: use scalars. Treat each column individually and assign scalar values. This can be a viable solution if you working with a fixed, small number of columns (e.g. RGB channels):
>> a = [245,255,255;254,252,255;251,250,239]
a =
245 255 255
254 252 255
251 250 239
>> idx = [1;3];
>> a(idx,1) = vec(1);
>> a(idx,2) = vec(2);
>> a(idx,3) = vec(3)
a =
255 100 0
254 252 255
255 100 0
This can also be trivially looped ( I am sure that you can see how).
3 件のコメント
その他の回答 (2 件)
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!