Reputation: 3
I have 6
stations and 3
from it are unstable. The unstable stations uspt
are, say 2, 3, 6
.
Each station represents two columns and two rows e.g station 1 correspond to the rows 1 and 2, station 2 corresponds to the rows 3 and 4 and so on. First two columns correspond to the first unstable station which is station 2. Next two columns (columns 3 and 4) correspond to the next unstable station which is station 3 and so on.
I want to create a matrix B
which assigns number 1
for unstable points using the above information and zeros to all other points. So for the given number of total stations and unstable of them, following is the desired output:
B = [0 0 0 0 0 0
0 0 0 0 0 0
1 0 0 0 0 0
0 1 0 0 0 0
0 0 1 0 0 0
0 0 0 1 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 1 0
0 0 0 0 0 1]
Here is what I have tried:
%my input
stn=6; %no of stations
us=3; %no of unstable stations
uspt=[2 3 6] %unstable station
m=stn*2; %size of matrix, no of row
u=(stn)-us; %no of stable station
n=m-2*u; %no of column
B = zeros(m,n);
io=uspt(2:2:length(uspt));ie=uspt(1:2:length(uspt)); %ie=even numb/io=odd numb
for ii=numel(B+1,2)
if ie>0|io>0
ii=ii+1;
B(ie*2-1,ii-1)=1;B(ie*2,ii)=1;
ii=ii+1;
B(io*2-1,ii)=1;B(io*2,ii+1)=1;
end
end
B=B
And what I got:
B = [0 0 0 0 0 0
0 0 0 0 0 0
1 0 0 0 0 0
0 1 0 0 0 0
0 0 1 0 0 0
0 0 0 1 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
1 0 0 0 0 0
0 1 0 0 0 0]
I got the correct assignment for the 2
and 3
stations while wrong assignment position for 6
station. How can I achieved the correct assignment for 6
station or any station?
Upvotes: 0
Views: 71
Reputation: 19689
You don't need a loop here.
m = stn*2; %Number of rows of the required matrix
n = numel(uspt)*2; %Number of columns of the required matrix
B = zeros(m,n); %Initializing B with all zeros
%finding row and column indices whose elements are to be changed
row = sort([uspt*2-1, uspt*2]); %sorted row indices
col = 1:n; %column indices
linInd = sub2ind([m,n], row,col); %Converting row and column subscripts to linear indices
B(linInd) = 1; %Changing the values at these indices to 1
Or as a two liner:
B = zeros(stn*2, numel(uspt)*2);
B(sub2ind([stn*2,numel(uspt)*2], sort([uspt*2-1, uspt*2]),1:numel(uspt)*2) = 1;
Upvotes: 1