Multiply Even Variables in an Array

I have initialized an array with values.
I have made a function that will determine if the integers within the array are odd or even. For the integers that are even, I want to multiply them by a set, finite number such as 5.
How would I do this?

답변 (1개)

Steven Lord
Steven Lord 2021년 2월 23일

0 개 추천

Hint: use logical indexing twice in the onle line of code that performs this replacement.

댓글 수: 8

Richard Dillenson
Richard Dillenson 2021년 2월 23일
I don't understand why I cannot do *=10 but I am able to assign them new finite values.
There's no such thing as a *= operator in MATLAB. But you have gotten half the solution:
x(rem(x, 2) == 0) =
That refers to the even elements in x on the left side. Now you need to figure out how to use logical indexing on the right of the equals sign.
Richard Dillenson
Richard Dillenson 2021년 2월 24일
I cannot figure this out based upon the link you sent above. Can I get another hint?
Just use a variable to store the logical indexes. E.g.,
ix = rem(x,2)==0;
Then use ix for indexing downstream in your code.
Steven Lord
Steven Lord 2021년 2월 24일
You want to take the even numbers from their locations in x, multiply them by 5, then stick the results back in the locations of the even numbers in the original x vector. Your left side does the "then stick the results back in the locations of the even numbers in the original x vector" piece. Given that's what it does, how would you do the "take the even numbers from their locations in x, multiply them by 5" piece?
Richard Dillenson
Richard Dillenson 2021년 2월 24일
x(rem(x, 2) == 0) = x(rem(x,2)*5;
Thank you so much!
James Tursa
James Tursa 2021년 2월 24일
This is not correct. You need to use the exact same indexing on both sides of the assignment.
Steven Lord
Steven Lord 2021년 2월 24일
There are also mismatched parentheses. From the fact that Richard Dillenson said "Thank you" I assume that's an error when the solution was copy-and-pasted into Answers not an error in the code they ran.

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Logical에 대해 자세히 알아보기

질문:

2021년 2월 23일

댓글:

2021년 2월 24일

Community Treasure Hunt

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

Start Hunting!

Translated by