program tip

MATLAB의지도 기능?

radiobox 2020. 8. 27. 07:39
반응형

MATLAB의지도 기능?


MATLAB에 Map 기능이 없다는 사실에 조금 놀랐습니다. 그래서 내가 없이는 살 수없는 것이기 때문에 직접 해킹했습니다. 더 나은 버전이 있습니까? 내가 놓친 MATLAB 용 다소 표준 함수 프로그래밍 라이브러리가 있습니까?

function results = map(f,list)
% why doesn't MATLAB have a Map function?
results = zeros(1,length(list));
for k = 1:length(list)
    results(1,k) = f(list(k));
end

end

사용법은 예입니다.

map( @(x)x^2,1:10)

짧은 대답 : 내장 함수는 숫자 형 배열에 대해 함수가 arrayfun수행하는 작업을 정확히 map수행합니다.

>> y = arrayfun(@(x) x^2, 1:10)
y =

     1     4     9    16    25    36    49    64    81   100

유사하게 작동하는 두 가지 다른 내장 함수가 있습니다. cellfun(셀형 배열의 요소에서 작동) 및 structfun(구조의 각 필드에서 작동).

그러나 벡터화, 특히 요소 별 산술 연산자를 사용하는 경우 이러한 함수는 종종 필요하지 않습니다 . 당신이 준 예에서 벡터화 된 솔루션은 다음과 같습니다.

>> x = 1:10;
>> y = x.^2
y =

     1     4     9    16    25    36    49    64    81   100

일부 연산은 요소간에 자동으로 작동하며 (예 : 벡터에 스칼라 값 추가) 다른 연산자는 요소 별 연산을위한 특수 구문 ( .연산자 앞에으로 표시됨 )이 있습니다. MATLAB의 많은 내장 함수는 요소 별 연산 (종종 예를 들어 sum같은 주어진 차원에 적용됨)을 사용하여 벡터 및 행렬 인수에서 작동하도록 설계되었으므로 mean맵 함수가 필요하지 않습니다.

요약하면 다음은 배열의 각 요소를 제곱하는 몇 가지 다른 방법입니다.

x = 1:10;       % Sample array
f = @(x) x.^2;  % Anonymous function that squares each element of its input

% Option #1:
y = x.^2;  % Use the element-wise power operator

% Option #2:
y = f(x);  % Pass a vector to f

% Option #3:
y = arrayfun(f, x);  % Pass each element to f separately

물론 이러한 간단한 작업의 경우 옵션 # 1이 가장 현명하고 효율적인 선택입니다.


벡터 및 요소 별 연산 외에도 cellfun셀형 배열에 대한 함수 매핑 있습니다. 예를 들면 :

cellfun(@upper, {'a', 'b', 'c'}, 'UniformOutput',false)
ans = 
    'A'    'B'    'C'

'UniformOutput'이 참 (또는 제공되지 않음)이면 셀형 배열의 차원에 따라 결과를 연결하려고 시도하므로

cellfun(@upper, {'a', 'b', 'c'})
ans =
ABC

Matlab의 벡터화를 사용하는 다소 간단한 솔루션은 다음과 같습니다.

a = [ 10 20 30 40 50 ]; % the array with the original values
b = [ 10 8 6 4 2 ]; % the mapping array
c = zeros( 1, 10 ); % your target array

자, 타이핑

c( b ) = a

보고

c = 0    50     0    40     0    30     0    20     0    10

c (b)는 b로 주어진 인덱스에 c 요소가있는 크기 5의 벡터에 대한 참조입니다. 이제이 참조 벡터에 값을 지정하면 c (b)에 c의 값에 대한 참조가 포함되고 복사본이 없기 때문에 c의 원래 값을 덮어 씁니다.


필요한 결과가 함수의 배열 인 경우 내장 arrayfun이 작동하지 않는 것 같습니다. 예 : map (@ (x) [xx ^ 2 x ^ 3], 1 : 10)

slight mods below make this work better:

function results = map(f,list)
% why doesn't MATLAB have a Map function?
for k = 1:length(list)
    if (k==1)
        r1=f(list(k));
        results = zeros(length(r1),length(list));
        results(:,k)=r1;
    else
        results(:,k) = f(list(k));

    end;
end;
end

If matlab does not have a built in map function, it could be because of efficiency considerations. In your implementation you are using a loop to iterate over the elements of the list, which is generally frowned upon in the matlab world. Most built-in matlab functions are "vectorized", i. e. it is more efficient to call a function on an entire array, than to iterate over it yourself and call the function for each element.

In other words, this


a = 1:10;
a.^2

is much faster than this


a = 1:10;
map(@(x)x^2, a)

assuming your definition of map.


You don't need map since a scalar-function that is applied to a list of values is applied to each of the values and hence works similar to map. Just try

l = 1:10
f = @(x) x + 1

f(l)

In your particular case, you could even write

l.^2

Vectorizing the solution as described in the previous answers is the probably the best solution for speed. Vectorizing is also very Matlaby and feels good.

With that said Matlab does now have a Map container class.

See http://www.mathworks.com/help/matlab/map-containers.html

참고URL : https://stackoverflow.com/questions/983163/map-function-in-matlab

반응형