# 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

2 views (last 30 days)

Show older comments

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

##### 3 Comments

Geoff Hayes
on 25 Feb 2015

### Answers (2)

Image Analyst
on 25 Feb 2015

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 Comments

Image Analyst
on 25 Feb 2015

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
on 25 Feb 2015

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

##### 0 Comments

### See Also

### Community Treasure Hunt

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

Start Hunting!