Multiplying every secound element in a vector with -1
2 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Jonathan Larsson
il 1 Ott 2019
Risposto: James Tursa
il 3 Ott 2019
Hello I am looking for how to multiply every secound element in vector 1xn with -1, but I want to write this as a function. I can do this manually like this for example with an 1x3 vector;
function vny = byt_tecken(v)
vny=[v(1,1),-v(1,2),v(1,3)]
end
But how do I do this for any given 1xn vector? Thanks!
0 Commenti
Risposta accettata
John D'Errico
il 1 Ott 2019
Modificato: John D'Errico
il 1 Ott 2019
You need to start learning MATLAB. That is, actually learn to use vectors, matrices, not just work with single numbers, and loops. Until you do, you will continue to have these problems.
Here is one way to do what you asked for. There are surely a zillion others.
v = 1:10;
vny = v.*(mod(1:numel(v),2)*2 - 1)
vny =
1 -2 3 -4 5 -6 7 -8 9 -10
The point is to start thinking in terms of a vector and vector operations, tools that operate on every element of a vector in one call.
0 Commenti
Più risposte (2)
Daniel M
il 3 Ott 2019
Here is another way:
function vny = byt_tecken(v)
vny = v.*-(-1).^(1:numel(v));
end
0 Commenti
James Tursa
il 3 Ott 2019
Or yet another of the zillion ways
vny = v;
vny(2:2:end) = -vny(2:2:end);
0 Commenti
Vedere anche
Categorie
Scopri di più su Logical in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!