Adding 1 to odd numbers and 2 to even values of a matrix in an m file in MATLAB

I want to add 1 to all the odd numbers and 2 to all of the even numbers of my matrix. I think you can use an if statement and a "mod" function, but I'm not sure how. can anyone help??
b= input('Enter a value for b');
c= input('Enter a value for c');
d= input('Enter a value for d');
e= input('Enter a value for e');
a= [b c; d e];
for i =1:2
for j =1:2
if i==1
if j==1
a(i,j)= a(i,j)+1;
end
end
if i==1
if j==2
a(i,j)= a(i,j)+2;
end
end
if i==2
if j==1
a(i,j) = a(i,j)+3;
end
end
if i==2
if j==2
a(i,j) = a(i,j)+4;
a = [a(2,1),a(2,2);a(1,1),a(1,2)];
end
end
end
end

Answers (2)

M = magic(3); %example matrix
idx = ~mod(M,2); %even places
M(idx) = M(idx)+2;
M(~idx) = M(~idx)+1;

2 Comments

Order doesn't matter as idx is not going to change with the calculation.
Very true. I didn't originally predefine idx.

Sign in to comment.

Categories

Tags

Asked:

on 12 May 2011

Community Treasure Hunt

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

Start Hunting!