issue with saving matrix in for loop

Hi,
I am creating a big matrix 'U' in the for loop as shown below. After this I have to avergae this matrix.
As long as, if my 'kk' is contonous i.e. from 1 to 10000, i dont have any issue. But, for sometimes, my 'kk' is discontinous, for e.g. 5, 7, 11, 18, 23, here logically I should get U matrix of a x b x 5, beacuse I have read only 5 files. However, I end up with a x b x 23, this changes my average value. Is there any way to get rid of this ??...
for kk = 1:1:10000
U(:,:,kk) = fu2;
end

 Risposta accettata

The index being assigned to in your code is based on the loop variable (kk). If you assign to index 23, you will have a matrix with dimension at least 23, though it may be mostly empty.
By adding a second variable tracking your matrix index, you can reduce this dimension:
U = [];
index = 1
for kk = 1:3:10000
U(:,:,index) = fu2;
index = index + 1;
end
In this example code, I simulate your discontinuous kk by adding 3 each time instead of 1. The result is that U has dimension 3334 instead of 10000.

Più risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements in Centro assistenza e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by