Creating a random matrix with conditions without using iteration

Is it possible to make a matrix using rand where all values less than a certain value, such as 5, are replaced by 0? Without any iteration by the way.
I know you can just do:
A=10*rand(5,5);
A=(A(:,:)>5).*A(:,:)
But this iterates off the previous declaration.

1 件のコメント

Gregory Shoemake
Gregory Shoemake 2016 年 10 月 5 日
I'm beginning to wonder if maybe I'm just misunderstanding the meaning of iteration. Pretty new to MatLab so please excuse if this is common knowledge.

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

回答 (3 件)

Jan
Jan 2016 年 10 月 5 日

0 投票

This is fine:
A = (A>5) .* A
There is not reason to avoid this. Using 2 lines instead of one is not a drawback.
An "iteration" means a loop usually. So you code does not contain an iteration (if we ignore that Matlab uses loops internally to process the elements of the array).

1 件のコメント

Gregory Shoemake
Gregory Shoemake 2016 年 10 月 5 日
Thank you! really cleared things up. Also can I ask how I might complete the same task using iteration?

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

Jos (10584)
Jos (10584) 2016 年 10 月 5 日

0 投票

A = [1 5 3 2 4]
A(A>3) = 0 % all at once, the way to go!!
B = [1 5 3 2 4]
for k=1:numel(B), % iteration over each element of B
if B(k) > 3,
B(k) = 0 ;
end ;
end

カテゴリ

ヘルプ センター および File ExchangeCreating and Concatenating Matrices についてさらに検索

質問済み:

2016 年 10 月 5 日

回答済み:

2016 年 10 月 5 日

Community Treasure Hunt

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

Start Hunting!

Translated by