フィルターのクリア

Create a matrix "z" which has the same elements as "x". If any entry in "z" % is even, increase that entry by one.

3 ビュー (過去 30 日間)
Hello,
Can anyone helo me with this one?
Create a matrix "z" which has the same elements as "x". If any entry in "z" is even, increase that entry by one.

採用された回答

SAA
SAA 2020 年 7 月 26 日
編集済み: SAA 2020 年 7 月 26 日
What is the part that you're stuck on?
you need to use a for loop and an if else like this:
.... % defining your variables and all that
for i=1:numel(z)
if mod(z(i),2) == 0 % thats how to see if it's even or not
z(i) = z(i)+1; % something like this
end
end
  2 件のコメント
STAVROS GALANOS
STAVROS GALANOS 2020 年 7 月 26 日
Thank you SSA!
I am very new to this and i was not aware of the function 'numel()'. So i was trying to change only the even values but the result was to change all values or no values at all.
cheers !
Stephen23
Stephen23 2020 年 7 月 26 日
編集済み: Stephen23 2020 年 7 月 26 日
"you need to use a for loop and an if else like this:"
Not true. With MATLAB, neither a loop nor if-else is required, basic logical indexing works perfectly:
>> x = randi(9,3,5)
x =
6 5 3 4 7
5 1 6 7 7
8 8 5 9 4
>> z = x;
>> y = mod(z,2)==0;
>> z(y) = z(y)+1
z =
7 5 3 5 7
5 1 7 7 7
9 9 5 9 5
as do several other even simpler methods which do not require loops or if-else:
>> z = x + ~mod(x,2)
z =
7 5 3 5 7
5 1 7 7 7
9 9 5 9 5
If you are using loops and if-else to solve basic problems like this, then you are not learning how to use MATLAB.

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

その他の回答 (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