Why is my iteration not working?
2 次查看(过去 30 天)
显示 更早的评论
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'?
采纳的回答
Binaya
2023-9-26
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
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!