Modifying odd/even numbers of a column vector

29 ビュー (過去 30 日間)
Matt Smith
Matt Smith 2021 年 2 月 24 日
コメント済み: Matt Smith 2021 年 2 月 24 日
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.

採用された回答

Rik
Rik 2021 年 2 月 24 日
If you have trouble with Matlab basics you may consider doing the Onramp tutorial (which is provided for free by Mathworks).
x = [4 5 7 6 5 8 2 1];
%with simple indexing:
x(1:2:end)=2*x(1:2:end);
disp(x);
8 5 14 6 10 8 4 1
%or with logical indexing with mod:
L=mod(x,2)==0;
x(L)=2*x(L);
disp(x);
16 5 28 12 20 16 8 1
  1 件のコメント
Matt Smith
Matt Smith 2021 年 2 月 24 日
Thank you!

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

その他の回答 (1 件)

Hernia Baby
Hernia Baby 2021 年 2 月 24 日
編集済み: Hernia Baby 2021 年 2 月 24 日
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 件のコメント
Rik
Rik 2021 年 2 月 24 日
Note that you made a small typo: you should have used == to compare the output of mod to 1 or 0.
Hernia Baby
Hernia Baby 2021 年 2 月 24 日
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);

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

カテゴリ

Help Center および File ExchangeVariables についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by