Change sign of every second element of a vector

29 ビュー (過去 30 日間)
am
am 2019 年 3 月 22 日
編集済み: madhan ravi 2019 年 3 月 22 日
Hi,
I want to change the sign of every second element in a vector, starting from element two. I tried the following code. Can someone explain why it does not work and help me to fix it? Thank you!
function newVector = change(v)
for i = 1:length(v)-1
newVector(i) = v(i);
newVector(i+1) = v(i+1)*-1;
end
v = newVector
end
  1 件のコメント
madhan ravi
madhan ravi 2019 年 3 月 22 日
編集済み: madhan ravi 2019 年 3 月 22 日
@KSSV: Why did you delete my comment ?

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

採用された回答

KSSV
KSSV 2019 年 3 月 22 日
編集済み: KSSV 2019 年 3 月 22 日
A = rand(10,1) ;
A(2:2:end) = -A(2:2:end)
If you wat to your function, you should use like this:
function newVector = change(v)
newVector = v ;
for i = 1:length(v)
if ~mod(i,2)
newVector(i) = -v(i);
end
end
  3 件のコメント
am
am 2019 年 3 月 22 日
Great, that did the job finely!
KSSV
KSSV 2019 年 3 月 22 日
@am You can see that I have a given a snippet using loop also..you may compare your code and the present one and you can analyse the problem in your code. Like this you can learn on your own. Coding need not to be explained....it should be learnt on your own.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeStatistics and Machine Learning Toolbox についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by