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

25 views (last 30 days)
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]

Accepted Answer

James Tursa
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.
  1 Comment
hbcukid
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
part but will try to do additional reading

Sign in to comment.

More Answers (0)

Categories

Find more on Characters and Strings in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!