MATLAB: Is there any way of joining these two for loops into one

for loop

I have two for loops which do the same thing to an array and I would like to join them together (if possible) to make my code tidier. Here are my two for loops.
for i = 1:K
A(i,:,:)=B(i,:,:)
end
for i = (n+1-K):n
A(i,:,:)=B(i,:,:)
end
How do i write the same thing in one for loop? Any responses would be really appreciated, thank you.

Best Answer

You don’t need any for-loops at all. Do this:
A([1:K,n+1-K:n],:,:) = B([1:K,n+1-K:n],:,:);
If you insist on one loop, do this:
for ix = [1:K,n+1-K:n]
A(ix,:,:) = B(ix,:,:);
end
Related Question