Loop in a loop question?

조회 수: 1 (최근 30일)
bio lim
bio lim 2015년 6월 21일
댓글: Jan 2015년 6월 22일
I have a 1 x 521 structure array called 'data' with 20 fields. One of the field is 'GS', which stands for Ground speed. I am trying to find the instantaneous Ground Speed for all arrays, and make a new field called 'instantaneous_GS'. The following is the code I am using.
for n = 1 : length(data)
for i = 1 : length(data(n).GS)
data(n).instantenous_GS = (data(n).GS(i) + data(n).GS(i + 1))/2;
end
end
I am a new MATLAB user, and have no clue what is the problem with my code. Can anyone help me? Thanks.
  댓글 수: 1
Jan
Jan 2015년 6월 22일
You forgot to mention why you assume, that there is a problem at all. Do you get an error message?

댓글을 달려면 로그인하십시오.

채택된 답변

Image Analyst
Image Analyst 2015년 6월 21일
To get all the GS values in to one array, use the [] operator to concatenate them all then conv() to get the array of means (the average between pairs like you were doing)
for k = 1 : length(data)
data(k).instantaneous_GS = conv([data(k).GS], [.5, .5], 'valid')
end
  댓글 수: 1
Guillaume
Guillaume 2015년 6월 22일
data(k).GS is already an array, so the [] are actually unnecessary. It would be required if you were accessing multiple elements of the data array:
[data(:).GS]
This is actually a neat way of getting the mean of consecutive elements of an array. However, as the purpose of the conv is not immediately obvious, I would strongly recommend adding a comment explaining what is happening.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Guillaume
Guillaume 2015년 6월 21일
Possibly, you meant to do:
for dataidx = 1 : numel(data)
data(dataidx).instantenous_GS = mean([data(dataidx).GS(1:end-1); data(dataidx).GS(2:end)]);
end
If not, you need to explain the relationship between instantaneous_GS and GS.

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by