For loop inside structure

조회 수: 1 (최근 30일)
Mohammed Hammad
Mohammed Hammad 2019년 1월 24일
편집: Mohammed Hammad 2019년 1월 26일
I have a structure called (level3) and inside it some fields (e.g x0, vx). each field is an array with some values as shown in the screenshot.
I would like to go through these fields values and multply them as follows:
x(1,1)*vx(1,1)
x(2,1)*vx(2,1)
x(3,1)*vx(3,1)
.... and so on.
so I got at the end 10 arrays of results of x
I tried to do it like this but I just got one array with the last value.
fields = fieldnames(level3);
for k=1:10
x = [x0. * vx];
end
Thanks in advance

채택된 답변

Mohammed Hammad
Mohammed Hammad 2019년 1월 25일
편집: Mohammed Hammad 2019년 1월 26일
I got the answer after many tries as follows:
for n = 1:10
x{n} = level3(n).x0. * (level3(n).vx)
end
  댓글 수: 2
Stephen23
Stephen23 2019년 1월 26일
편집: Stephen23 2019년 1월 26일
Those square brackets are superfluous. Get rid of them.
Note that your inner loop serves no purpose, because you do not use its loop index anywhere and none of its iterations depend on previous iterations, so the results of every of its iteration will get discarded except for the last one.
Mohammed Hammad
Mohammed Hammad 2019년 1월 26일
Thank you for your notes. yeah I removed the inner loop and I got the desired results.

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

추가 답변 (1개)

Bob Thompson
Bob Thompson 2019년 1월 24일
fields = fieldnames(level3);
for k=1:10
x = [x0. * vx];
end
If I understand this correctly you're trying to capture the array of multiplications (x0 .* vx) for all of the different elements of the structure. I believe that all you're missing then is either an index on x, or to concatonate the results of x with the previous values.
fields = fieldnames(level3)
x = [];
for k = 1:10
x = [x;[x0.*vx]];
end
  댓글 수: 1
Mohammed Hammad
Mohammed Hammad 2019년 1월 25일
It works , thank you. but the answer is Double(50*1) and I want it 10 arrays, each array has different number of values. the length must be the same as x0 and vx arrays length

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

카테고리

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

제품


릴리스

R2016a

Community Treasure Hunt

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

Start Hunting!

Translated by