Nested / parfor loop issue

1 view (last 30 days)
Micheal Simpson
Micheal Simpson on 4 Jan 2016
Commented: Brendan Hamm on 5 Jan 2016
I am currently trying to run a loop while concurrently running another loop. However, the two different loops do not match in terms of stepping which is giving me some issues.
For example, let's say I have a matrix January, with dimensions (24,6,31) for 24 hours, 6 columns of data, and 31 days that is empty. I want to put data into this matrix from a master matrix, that is 744 x 6 (744 hours in the month of January with the 6 columns of data).
Now, to simply put the first days worth of data into the January matrix, I have: January(:,:,1) = Master(1:24,1:6) The second day would be: January(:,:,2) = Master(25:48,1:6) etc. etc.
What would be the easiest way to loop through this? I have..
January = zeros(24,6,31); for i = 1:24:744 for j = 1:31 January(:,:,j) = Data(i:i+23,1:6); end end
But, this is obviously not correct. Using the parfor function gives me an error because the step between i and j are not the same. Any help would be greatly appreciated!

Accepted Answer

Brendan Hamm
Brendan Hamm on 4 Jan 2016
a) You must be trying to use parfor on the outer i loop, but this does not allow you to make an assignment to the jth page of January as parfor will not allow this.
b) Why do you need a loop? (See vectorized example)
c) Why do you need to do this in parallel? (This is not a large problem, but if you want just move the parfor to the inside loop)
Try to use vectorization:
% Create a matrix to represent your data:
S = (1:744*6)';
S = reshape(S,744,6); % S now has the format you mentioned
% Now we can just do a reshape on the transposed data and then permute:
S2 = reshape(S.',6,24,[]);
S3 = permute(S2,[2 1 3]);
  2 Comments
Micheal Simpson
Micheal Simpson on 4 Jan 2016
Many thanks, this is a much better approach!
However, from my data, I get instances where the data is multiplied by 1.0e+003 (only if there is data in columns 5 and 6). How does one make this.. not happen? The data is is no more than 3 decimal places long (i.e., data > 0.0009)
Brendan Hamm
Brendan Hamm on 5 Jan 2016
I assume you are talking about the display format. If this is the case you should know that the actual data being stored is to double precision, just the view of that data appears in this manner for easier readability.
You can always change the display format.

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!