How to change the elements of a matrix based on row/column numbers?
Ältere Kommentare anzeigen
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 Kommentar
the cyclist
am 25 Aug. 2014
An example of inputs, along with the output you expect from those inputs, would help us help you.
Antworten (1)
Andrei Bobrov
am 25 Aug. 2014
l=2;r=4;b=3;t=5;
P=ones(6,6);
P(l:r,7 - (b:t)) = 2;
2 Kommentare
if the number of row and columns is equal you can write:
P=ones(6);
and for any n:
n=6;
P = ones(n);
P(l:r,7 - (b:t)) = 2;
José-Luis
am 25 Aug. 2014
If it's for any n then it should be:
P(l:r,size(P,2) + 1 - (b:t)) = 2;
Kategorien
Mehr zu Resizing and Reshaping Matrices finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!