Inserting Spaces a consistent intervals in data using nested for loops.

Hello, I'm having trouble with this piece of code. I'm sill fairly new to matlab which is probably why I'm struggling.
I've imported data into matlab in an 84x8 matrix (tracingdata). What I need to do is put 4 rows of NaN inbetween each row in that matrix. First, I've created a second matrix to put the new data in that is 420x8 (called Chart).
chart = NaN(420,8)
Next, I put the first row of tracing data as the first row in chart as a starting point for the for loop
chart(1,:) = tracingdata(1,:)
Finally, I attempted to create a nested for loop. The first for loop reads the tracing data matrix, and nested for loop puts rows of tracing data in at intervals of 4 into the chart matrix. The problem is that this part of the code doesn't work. When I evaluate it I end up with my chart matrix 420x8 with the very frist row having the same first row of tracingdata (which is what I want). But the rest of the chart matrix is filled with NaNs and no other data.
for i=1:1:size(tracingdata)
tracingdata(i,:)=chart(j,:)
for j=1:4:size(chart)
end
end
Any suggestions would be great. I have a feeling it's something simple, I just can't seem to wrap my head around it
- Kyle

 Risposta accettata

This works:
tracingdata = randi(10, 84, 8); % Created Data
chart = NaN(420,8);
NaNsep = 5;
chart(1:NaNsep:NaNsep*84,:) = tracingdata(1:84,:);
check_result = chart(1:16,:) % Verify Correct Format
You can discard the ‘check_result’ assignment if its output verifies that the ‘chart’ matrix is what you want. I created a separate ‘NaNsep’ variable in the event you want to change the spacing.

4 Commenti

This works great, thank you!
chart(1:NaNsep:NaNsep*84,:) this part you deisignated starting at the first row. with intervals of 5. why multiply it by 84 though?
Also, theoretically, if the size of tracing data changed to say 100x8. Could I replace
chart(1:NaNsep:NaNsep*84,:) = tracingdata(1:84,:);
with
chart(1:NaNsep:NaNsep*size(tracingdata,:) = tracingdata
i actually just tested that and it worked. thank you^^ - Kyle
The multiplication simply makes certain that the dimensions work out correctly. (I don’t like to leave such to chance!)
You’re almost there. You need to change that line to:
chart(1:NaNsep:NaNsep*size(tracingdata,1),:) = tracingdata(1:size(tracingdata,1),:);
because ‘size(tracingdata,1)’ gives you the row size (dimension #1) of ‘tracingdata’, which is what you want. (The call ‘size(tracingdata,:)’ will throw an error.) See the documentation for size for details.
I ran my code with these changes in that line to be sure it works. (It does.)

Accedi per commentare.

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