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 ExchangeFunctions についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by