# How do I add an integer to every or any nth row

7 views (last 30 days)
hbcukid on 19 Nov 2020
Commented: hbcukid on 19 Nov 2020
Fairly new to MATLAB so I am just playing around to familiarize myself with it.
Lets say I have a 4x4 matrix, "A", how would I add for exaple 2 to every element in every other row (in this instance odd rows)? How would this differ if I wanted it for every nth row?
A = [1 1 0 0; 1 1 0 0; 0 0 0 0; 0 0 0 0]
desired output:
A = [3 3 2 2; 1 1 0 0; 2 2 2 2; 0 0 0 0]

James Tursa on 19 Nov 2020
Edited: James Tursa on 19 Nov 2020
A(k,:) is the k'th row of A
A(:,k) is the k'th column of A
A([k m p],:) is the sub-matrix formed from the k'th, m'th, and p'th rows of A
A(:,[k m p]) is the sub-matrix formed from the k'th, m'th, and p'th columns of A
A(1:5:end,:) is the sub-matrix formed from every 5'th row of A
A(:,1:5:end) is the sub-matrix formed from every 5'th column of A
etc.
To add a number to such sub-matrices, simply put them in an assignment
A(whatever) = A(whatever) + number;
The "whatever" is the indexing you want to pick off rows or columns etc.
hbcukid on 19 Nov 2020
Thank you so much, it worked! Still a little confused on the
A([k m p],:) is the sub-matrix formed from the k'th, m'th, and p'th rows of A
A(:,[k m p]) is the sub-matrix formed from the k'th, m'th, and p'th columns of A