development

MATLAB에 foreach가 있습니까?

big-blog 2020. 5. 30. 09:54
반응형

MATLAB에 foreach가 있습니까? 그렇다면 기본 데이터가 변경되면 어떻게 작동합니까?


MATLAB에 foreach 구조가 있습니까? 그렇다면 기본 데이터가 변경되면 (즉, 객체가 세트에 추가 된 경우) 어떻게됩니까?


MATLAB의 FOR 루프는 본질적으로 정적입니다. 다른 언어 for (initialization; condition; increment) 루프 구조 와 달리 반복 사이의 루프 변수를 수정할 수 없습니다 . 즉, 다음 코드는 B 값에 관계없이 항상 1, 2, 3, 4, 5를 인쇄합니다.

A = 1:5;

for i = A
    A = B;
    disp(i);
end

반복하는 동안 데이터 구조의 변경에 응답하려면 WHILE 루프 가 더 적합 할 수 있습니다.-매 반복마다 루프 조건을 테스트하고 루프 변수의 값을 설정할 수 있습니다 ( s) 원하는대로 :

n = 10;
f = n;
while n > 1
    n = n-1;
    f = f*n;
end
disp(['n! = ' num2str(f)])

Java (및 기타 언어) for-each 루프 반복 중에 데이터 구조가 수정 될 때 지정되지 않은 동작을 생성합니다. 데이터 구조를 수정해야하는 경우 반복하는 컬렉션에서 요소를 추가 및 제거 할 수 있는 적절한 Iterator 인스턴스를 사용해야합니다 . 좋은 소식은 MATLAB이 Java 객체를 지원하므로 다음과 같이 할 수 있다는 것입니다.

A = java.util.ArrayList();
A.add(1);
A.add(2);
A.add(3);
A.add(4);
A.add(5);

itr = A.listIterator();

while itr.hasNext()

    k = itr.next();
    disp(k);

    % modify data structure while iterating
    itr.remove();
    itr.add(k);

end

Zach은 그 질문에 대한 직접적인 대답에 대해 옳습니다.

흥미로운 참고 사항은 다음 두 루프가 동일하게 실행되지 않는다는 것입니다.

for i=1:10000
  % do something
end
for i=[1:10000]
  % do something
end

첫 번째 루프 i는 스칼라 인 변수 작성 하고 C for 루프처럼 반복합니다. 참고 수정할 경우 것으로 i자크가 말한대로 루프 본문에 수정 된 값은 무시됩니다. 두 번째 경우 Matlab은 10k 요소 배열을 만든 다음 배열의 모든 요소를 ​​걷습니다.

이것이 의미하는 것은

for i=1:inf
  % do something
end

작동하지만

for i=[1:inf]
  % do something
end

(이것은 무한 메모리를 할당해야하기 때문에) 아닙니다. 자세한 내용은 Loren의 블로그 를 참조하십시오.

또한 셀형 배열을 반복 할 수 있습니다.


MATLAB for 루프는 기본적으로 기능을 포함하여 큰 유연성을 허용 합니다. 다음은 몇 가지 예입니다.

1) 시작, 증분 및 종료 인덱스 정의

for test = 1:3:9
   test
end

2) 루프 오버 벡터

for test = [1, 3, 4]
   test
end

3) 루프 오버 스트링

for test = 'hello'
   test
end

4) 1 차원 셀 어레이에 루프

for test = {'hello', 42, datestr(now) ,1:3}
   test
end

5) 2 차원 셀 어레이에 루프

for test = {'hello',42,datestr(now) ; 'world',43,datestr(now+1)}
   test(1)   
   test(2)
   disp('---')
end

6) Use fieldnames of structure arrays

s.a = 1:3 ; s.b = 10  ; 
for test = fieldnames(s)'
   s.(cell2mat(test))
end

If you are trying to loop over a cell array and apply something to each element in the cell, check out cellfun. There's also arrayfun, bsxfun, and structfun which may simplify your program.


ooh! neat question.

Matlab's for loop takes a matrix as input and iterates over its columns. Matlab also handles practically everything by value (no pass-by-reference) so I would expect that it takes a snapshot of the for-loop's input so it's immutable.

here's an example which may help illustrate:

>> A = zeros(4); A(:) = 1:16

A =

     1     5     9    13
     2     6    10    14
     3     7    11    15
     4     8    12    16

>> i = 1; for col = A; disp(col'); A(:,i) = i; i = i + 1; end;
     1     2     3     4

     5     6     7     8

     9    10    11    12

    13    14    15    16

>> A

A =

     1     2     3     4
     1     2     3     4
     1     2     3     4
     1     2     3     4

When iterating over cell arrays of strings, the loop variable (let's call it f) becomes a single-element cell array. Having to write f{1} everywhere gets tedious, and modifying the loop variable provides a clean workaround.

% This example transposes each field of a struct.
s.a = 1:3;
s.b = zeros(2,3);
s % a: [1 2 3]; b: [2x3 double]
for f = fieldnames(s)'
    s.(f{1}) = s.(f{1})';
end
s % a: [3x1 double]; b: [3x2 double]

% Redefining f simplifies the indexing.
for f = fieldnames(s)'
    f = f{1};
    s.(f) = s.(f)';
end
s % back to a: [1 2 3]; b: [2x3 double]

Let's say you have an array of data:

n = [1    2   3   4   6   12  18  51  69  81  ]

then you can 'foreach' it like this:

for i = n, i, end

This will echo every element in n (but replacing the i with more interesting stuff is also possible of course!)


I think this is what the OP really wants:

array = -1:0.1:10

for i=1:numel(array)
    disp(array(i))
end

As of today (Feb 27), there is a new For-Each toolbox on the MATLAB File Exchange that accomplishes the concept of foreach. foreach is not a part of the MATLAB language but use of this toolbox gives us the ability to emulate what foreach would do.

참고URL : https://stackoverflow.com/questions/408080/is-there-a-foreach-in-matlab-if-so-how-does-it-behave-if-the-underlying-data-c

반응형