Modifying odd/even numbers of a column vector
Show older comments
How would I go about modifying the odd and even elements of the following vector ?
x = [4 5 7 6 5 8 2 1];
So that when run it can carry out either +,-,*,/,^ ?.
Also after the vectors have been changed the disp(x); shows all all elements, including ones not changed.
Accepted Answer
More Answers (1)
Hernia Baby
on 24 Feb 2021
Edited: Hernia Baby
on 24 Feb 2021
You can modyfiy each element with mod function.
x = [4 5 7 6 5 8 2 1];
x_odd = x(mod(x,2)==1); % odd element
x_even = x(mod(x,2)==0); % even element
mod
3 Comments
Matt Smith
on 24 Feb 2021
Rik
on 24 Feb 2021
Note that you made a small typo: you should have used == to compare the output of mod to 1 or 0.
Hernia Baby
on 24 Feb 2021
Thank you, Rik! I will modify my typo.
--------------------------------
To Matt
I got what you want to do.
Then, you can do this with logical indexing.
It is same with Rik's code.
times = 2;
x = [4 5 7 6 5 8 2 1];
idx_odd = mod(x,2) == 1; % odd element
x(idx_odd) = times * x(idx_odd);
disp(x);
Categories
Find more on MATLAB in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!