A vector is given v=[6, 3, -9, 10, 5, 0, -8, 11, -15]. write a matlab command the doubles the elements that are odd and raises the elements that are even to th power of 2

therefore the answer would be the new vector is 36 6 -18 100 10 0 64 22 -30

3 件のコメント

Geoff Hayes
Geoff Hayes 2015 年 2 月 25 日
Alaa - what exactly is your question? This class assignment seems straightforward so you should be able to figure this out using a for loop and if and else block.
Alaa Al Miqdadi
Alaa Al Miqdadi 2015 年 2 月 25 日
編集済み: Geoff Hayes 2015 年 2 月 25 日
v=[6, 3, -9, 10, 5, 0, -8, 11, 15]
i=1;
for k=1:length(v)
if rem (v(k),2)==0
nv(i)=(v(k)^2);
i=i+1
n=odd(v)
for k=1:n
if v(k)<0
v(k)=2*v(k);
end
disp('The new vector is: ')
disp(v)
I did this but I know something is wrong
Geoff Hayes
Geoff Hayes 2015 年 2 月 25 日
See Greig's answer below for structuring your code. You should be able to simplify it by using an if and else (there is no need for a second for loop, and it is unclear what you expect n=odd(v) to do). Within your loop, as you are doing now, check for even and then let your else handle the case where the number is odd.

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

回答 (2 件)

Image Analyst
Image Analyst 2015 年 2 月 25 日
If you want to avoid a loop and do it vectorized, try this:
evenIndexes = 2 : 2 : length(v);
oddIndexes = 1 : 2 length(v);
v(evenIndexes) = v(evenIndexes)........you finish it..
v(oddIndexes) = v(oddIndexes)........you finish it..
You already did the formulas in your code so it should be easy to put them in the code above.

2 件のコメント

Greig
Greig 2015 年 2 月 25 日
This works on the odd and even indices, is the question not about whether the contents are odd or even?
Yeah, after looking at his code more carefully, it looks like you're right. So the code for that would be
oddIndexes = mod(v, 2)
evenIndexes = ~oddIndexes

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

Greig
Greig 2015 年 2 月 25 日
Your loop structure above seems a little odd and has some missing "end"s. Try this for a basic loop structure...
for k=1:length(v)
if % something
% do something
else
% do something else
end
end
And check out
doc even
That should be enough to fix up your code

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

質問済み:

2015 年 2 月 25 日

コメント済み:

2015 年 2 月 25 日

Community Treasure Hunt

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

Start Hunting!

Translated by