Matrix addition in a loop in a random column

1 view (last 30 days)
I have written a code, in which a block of 1x1 gets added to a Matrix of zeros M=zeros(10,10); and shifts the block from round to round one position down. My Problem is, that the Block is fixed in Column 1 but I want it to be in a Random position in Line 1. How can I implement this?
The other Problem is, that I want this block to be bigger than just 1x1. I want it to be 2x2 big. So I guess the code for this is: M(1:2,1:2)=1; but when I just change every Vektor Like M(1)=M(1)+1; to M(1:2,1:2)=M(1:2,1:2)+1 it doesnt work.. so my question is, how can I change these 1x1 blocks to 2x2 blocks, randomly placed in Line 1, so that everything still works?
Y=10;
X=10;
Matrix=zeros(Y,X);
for n=0:6
Matrix(1)=Matrix(1)+1;
for k=2:Y
Test = Matrix(k)+1;
if Test == 1
Matrix(k-1) = 0;
Matrix(k) = 1;
disp(Matrix)
end
end
end
Thank you!

Accepted Answer

dpb
dpb on 31 Jul 2020
Must reference the same size section of array on LHS of an assignment as the RHS unless assign the entire LHS variable to RHS.
So if M is the large array and m is the smaller, then
szm=2; % define the size of m
m=ones(szm); % define square of 1s of szm x szm
...
M(i:i+szm-1,j:j+szm-1)=m; % assign m to M at 1,j location for upper rh corner of m
...
Do the same thing for the array of zeros to write at the previous location before the new location.
As for a random colum, just use
szM=size(M,1); % size of the matrix M
j=randi([1 szM]); % pick random integer between 1 and szM (size of M)
to pick the j column randomly for each iteration.

More Answers (0)

Categories

Find more on Operating on Diagonal Matrices in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!