TheRealFakeNews
TheRealFakeNews

Reputation: 8153

Replacing an entire matrix block (arbitrary size) in Matlab

I need to replace the last n+2 rows of a matrix with

myeye = eye(n+2, (n+1)^2); 

Is there anyway to do this besides doing it element wise?

Essentially, I'd like to do something like this

myMatrix((n+1)^2-(n+1):end) = myeye; %the index is just the last n+2 rows

Of course that's not legal, but that's what I'd like to do.

Upvotes: 0

Views: 212

Answers (2)

Eitan T
Eitan T

Reputation: 32930

You can do:

 myMatrix((end - size(myeye, 1) + 1):end, :) = myeye(:, 1:size(myMatrix, 2))

Pay attention to the use of the keyword end to obtain the last row index.

Also note that since myeye is basically an n-by-n unity matrix concatenated horizontally with a zeros matrix, you can achieve the same effect in a simpler way:

 myMatrix((end - n - 1):end, :) = eye(n + 2, size(myMatrix, 2))

Upvotes: 1

Autonomous
Autonomous

Reputation: 9075

a=randi(10,[30 7]);
aNew=a;
n=1;
if (n+1)^2>=size(aNew,2)
   nRows=size(aNew,2);
else
   nRows=(n+1)^2;
end
aNew(size(a,1)-(n+1):end,1:nRows)=eye(n+2, (n+1)^2); %This is where you actually replace a block.

Upvotes: 0

Related Questions