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
'program tip' 카테고리의 다른 글
ASP.NET MVC-TempData-좋은 방법 또는 나쁜 방법 (0) | 2020.08.27 |
---|---|
JavaScript에서 변수 할당은 어떻게 작동합니까? (0) | 2020.08.27 |
gcc / g ++를 사용하여 Linux에서 Windows 용으로 컴파일하는 방법은 무엇입니까? (0) | 2020.08.27 |
다른 프로그래밍 언어로 쉽게 번역 할 수 있도록 코드에 어떤 종류의 패턴을 적용 할 수 있습니까? (0) | 2020.08.27 |
PHP 5.4에서 엄격한 표준 비활성화 (0) | 2020.08.27 |