フィルターのクリア

How vectorize this loop

1 回表示 (過去 30 日間)
Luca Re
Luca Re 2023 年 7 月 23 日
コメント済み: Image Analyst 2023 年 7 月 23 日
x=8
a=magic(x)
b=[15 7 3 4 9 0 9 4] ====> 0 is important to test it
1 method with loop
c=a;
tic
for i=1:height(a)
for j=1:width(a)
if b(j)~=0
c(i,j)=min(a(i,j),b(j));
end
end
end
toc
tic
2 method with loop
z=a.*(~b>0)+min(a,b);
toc
isequal(c,z)
%cù
hi...I'm learning how to vectorize matrices...is it correct or can it be improved?

採用された回答

Bruno Luong
Bruno Luong 2023 年 7 月 23 日
編集済み: Bruno Luong 2023 年 7 月 23 日
repmat is not needed (thanks to auto expension)
columns = 8;
a = magic(columns);
b = [15, 7, 3, 4, 9, 0, 9, 4]; % ====> 0 is important to test it
b2 = b;
b2(b2 == 0) = inf;
% Find the minimum of a or b2
minValues = min(a, b2) % What you call "c"
minValues = 8×8
15 2 3 4 9 6 7 4 9 7 3 4 9 51 9 4 15 7 3 4 9 43 9 4 15 7 3 4 9 30 9 4 15 7 3 4 9 38 9 4 15 7 3 4 9 19 9 4 15 7 3 4 9 11 9 4 8 7 3 4 4 62 9 1
  1 件のコメント
Image Analyst
Image Analyst 2023 年 7 月 23 日
@Luca Re forgot to enter his release. I don't know when auto expansion was introduced (and it's hard to find out that year in the help documentation) so I gave the version with manual expansion just to make sure he had something that worked. Of course if your version works for him, then he has a recent version and this is even more vectorized than mine.

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

その他の回答 (1 件)

Image Analyst
Image Analyst 2023 年 7 月 23 日
Sounds a lot like a homework assignment, but I'm going to assume it's not and give one possible solution:
columns = 8;
a = magic(columns);
b = [15, 7, 3, 4, 9, 0, 9, 4]; % ====> 0 is important to test it
% Fill out b so that it's a matrix the same size as a
b2 = repmat(b, [columns, 1]);
% Get rid of zeros
b2(b2 == 0) = inf
b2 = 8×8
15 7 3 4 9 Inf 9 4 15 7 3 4 9 Inf 9 4 15 7 3 4 9 Inf 9 4 15 7 3 4 9 Inf 9 4 15 7 3 4 9 Inf 9 4 15 7 3 4 9 Inf 9 4 15 7 3 4 9 Inf 9 4 15 7 3 4 9 Inf 9 4
% Find the minimum of a or b2
minValues = min(a, b2) % What you call "c"
minValues = 8×8
15 2 3 4 9 6 7 4 9 7 3 4 9 51 9 4 15 7 3 4 9 43 9 4 15 7 3 4 9 30 9 4 15 7 3 4 9 38 9 4 15 7 3 4 9 19 9 4 15 7 3 4 9 11 9 4 8 7 3 4 4 62 9 1
  3 件のコメント
Stephen23
Stephen23 2023 年 7 月 23 日
"My sokution is not correct?"
That depends: are negative values within scope?
Luca Re
Luca Re 2023 年 7 月 23 日
編集済み: Luca Re 2023 年 7 月 23 日
In matrix "a" yes...in array "b" no Ok i understand...thank

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

カテゴリ

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