How to change the elements of a matrix based on row/column numbers?
6 views (last 30 days)
Show older comments
Say I have a 6*6 matrix of ones. P=ones(6,6).
I want to change a certain number of values to 2 inside this matrix based on their row/column numbers by specifying a boundary. I have written this code:
for i=1:m
for j=1:n
if ((( i > left ) && (i < (right))) && (( j> bottom ) && (j <top)))
P(i,j)=2;
end
end
end
I have specified the left, right, bottom, top values beforehand. E.g. 2,5,2,5. I want the output to be P =
1 1 1 1 1 1
1 1 1 1 1 1
1 1 2 2 1 1
1 1 2 2 1 1
1 1 1 1 1 1
1 1 1 1 1 1
i.e if i is between 2 and 5 (rows 3 and 4) and if j is between 2 and 5 (columns 2 and 5) then the values are changed to 2.
It doesn't however work.
I understand that I could just directly change the values, but I want to be able to change the values of the variables (m,n top, bottom, etc) and run the code as part of a program.
Should I be using another for loop instead of if?
Thank you!
1 Comment
the cyclist
on 25 Aug 2014
An example of inputs, along with the output you expect from those inputs, would help us help you.
Answers (1)
See Also
Categories
Find more on NaNs 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!