vector comparison - find and replace

Hi there,
I have a quick question: Suppose there are two vectors A(m,1) and C=zeros(m,1). Now I want to replace the element of C with one if it is at the position of the maximum value of the first N elements of A. And so on. To clarify here is an example:
A = [2 4 5 1 8 9]; N = 2; than C should be: C = [0 1 (as 4>2) 1 0 (as 5>1) 0 1 (as 9>8)]; My issue is, I need to do this using as few computational power as possible as it will be part of a Monte Carlo study.
Cheers and thank you in advance!
Sebastian

댓글 수: 1

Matthew Doveton
Matthew Doveton 2013년 5월 13일
편집: Matthew Doveton 2013년 5월 13일
Not sure that this is the most efficient way of doing this as I am very new to MATLAB myself:
A = input( 'Enter amount of random data ');
N = input( 'Enter comparisons ');
tic
A = floor(9*rand(1,A)); %Random data to test
Remainder = rem(length(A),N); %find remainder
%if not directly divisible
if Remainder
%pad with 0's if not divisible by N
A = [A zeros(1, N - Remainder)];
end
A = reshape(A,N,length(A)/N); %resize array so that each column has data to compare
C = A == repmat(max(A), size(A,1), 1); %find the maximum value in each column, compare
C = C(:)'; %set back to single dimension
toc
disp(C)
I think I have a grasp on what you are trying to achieve.

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

 채택된 답변

Andrei Bobrov
Andrei Bobrov 2013년 5월 13일
편집: Andrei Bobrov 2013년 5월 13일

1 개 추천

A = [2 4 5 1 8 9]; N = 2;
t = diff(reshape(A,N,[])) > 0;
C = reshape([~t;t],1,[]);
or
A1 = reshape(A,N,[]);
M = numel(A)/N;
[ii,ii] = max(A1);
C = zeros(size(A));
C(sub2ind([N,M],ii,1:M)) = 1;

추가 답변 (0개)

카테고리

도움말 센터 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by