Adding 1 to odd numbers and 2 to even values of a matrix in an m file in MATLAB
Show older comments
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)
Walter Roberson
on 12 May 2011
M = magic(3); %example matrix
M = M + 2 - mod(M,2);
1 Comment
Sean de Wolski
on 12 May 2011
You win Sir!
Sean de Wolski
on 12 May 2011
M = magic(3); %example matrix
idx = ~mod(M,2); %even places
M(idx) = M(idx)+2;
M(~idx) = M(~idx)+1;
2 Comments
Walter Roberson
on 12 May 2011
Order doesn't matter as idx is not going to change with the calculation.
Sean de Wolski
on 12 May 2011
Very true. I didn't originally predefine idx.
Categories
Find more on Creating and Concatenating Matrices 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!