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

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.

 Réponse acceptée

Roger Stafford
Roger Stafford le 1 Déc 2016
Modifié(e) : Roger Stafford le 1 Déc 2016
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

1 commentaire

The code with no loops is perfect, thank you. It was just a case of making my code shorter and neater.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by