Why is my iteration not working?
1 view (last 30 days)
Show older comments
I have an example of how to find the difference of elements of a matrix starting on the 2nd iteration which would correlate with the 2nd row and j=1 is corresponding to the column. So This example Shows the difference of 2nd row - 1st row on the first column all the way to the last column.
Then next iteration will do 3rd row - 2nd row on the first column all the way to the last column and replace all those difference into the 'u' matrix.
This example is successful with the first column of 'u' being zeros and the rest being all different non-zero values.
a = rand(30,1,51);
u = zeros(30,1,51);
for i=2:numel(u(1,:,:)
for j =1:numel(u(:,:,1))
u(j,:,i) = (a(j,:,i) - a(j,:,i-1));
end
end
squeeze(u)
squeeze(a)
Now This is the problem that is similar to the example but, I cant seem to figure out why my 'u' is all zeros still.
All LatPos positions in the matrix for the first 15 rows and all columns are all different values. So 'u' should be a non-zero scalar at each position
function [LatPos, u] = fcn(detections)
LatPos = zeros(numel(detections.Detections),numel(detections.Detections(1).Time)) %LatPos = zeros[30x51]... Ends up becoming [30x1x51]
%detections.Detections = [30x1]
%detections.Detections(1).Time = [1x1x51]
u = zeros(numel(detections.Detections),numel(detections.Detections(1).Time)) %% u = zeros[30x51]... Ends up becoming [30x1x51]
for i = 2:numel(u(1,:,:))
for j = 1:numel(u(:,:,1)
u(j,:,i) = LatPos(j,:,i) - LatPos(j,:,i-1)
end
end
Could the issue be in the initialization of my matrices for both 'u' or 'LatPos'?
10 Comments
Accepted Answer
Binaya
on 26 Sep 2023
Hi Marshal,
I understand that you want to calculate difference of adjacent rows of a given matrix and store it in a separate matrix. For this task, you can use a single loop instead of two “for loops” the difference by using MATLAB indexing which will simplify the code and increase its readability.
Please find the simplified code below:
for i =2:numel(u(:,:,1))
u(i,:,:) = LatPos(i,:,:) - LatPos(i-1,:,:)
end
The code submitted by you had columns and row indices interchanged, which is fixed in the above code and also simplified so as not to use multiple “for loops” to access each individual element of the matrix.
I hope this helps.
Regards
Binaya
More Answers (0)
See Also
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!