简体   繁体   中英

Changing every other row in a matrix in R

Would anyone be able to show me a way of changing every second row in a column of a matrix to have the opposite sign to the one it currently has (eg changing a 4 to -4, or a -4 to 4)? I can do it with a for loop, but I was hoping there might be a more efficient method for doing it.

If you have an even number of rows, try

c(1,-1)*M

Where M is your matrix.

Otherwise, use

(2*(row(M) %% 2)-1)*M

EDIT: Carl Witthoft's suggestion:

rep(c(1,-1),length=nrow(M))*M

works with any matrix.

最终答案: rep(c(1,-1),length=nrow(M))*M

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM