Walter Roberson <roberson@hushmail.com> wrote in message <YZztl.34792$Hy7.27465@newsfe25.iad>...
> Sam Van der Jeught wrote:
>
> > I am looking for the best way to write an algorithm which must do the following:
> > given two matrices of the same size which have the same elements per row, but at different columns,
> > build a third matrix of the same size by:
> >
> > checking at every position whether or not the two original matrices have the same value,
> > if they do, the value of the third matrix should be this value,
> > for the values that don't, they should be 'shuffled' in their respective row.
>
> You need to clarify for the shuffling whether it is acceptable for a
> value to be "randomly suffled" to the same place that it started from, or
> whether everything must move? And suppose that you have two different
> columns that happen to have the same numeric value and both values are
> to be moved (because they don't happen to match the respective columns
> in the other matrix), then is it acceptable for the shuffle to happen
> to shuffle "in" the same numeric value that happened to be there before,
> or if each column that is not being preserved must end up a different
> numeric value than it was before?
>
> If shuffling "with replacement" is allowed, then
>
> C = A;
> for RowNum = 1:size(A,1)
> loc_of_diffs = find(A(RowNum,:) ~= B(RowNum,:));
> newpos = loc_of_diffs( randperm(length(loc_of_diffs)) );
> C(RowNum, newpos) = C(RowNum, loc_of_diffs);
> end
>
> But if the values must end up different than before, then the code
> becomes more difficult.
Here is a vectorized solution (just for fun):
% example data
A = [1 2 3 4 ; 0 8 8 7 ; 2 7 9 7] ;
B = [ 4 1 3 2 ; 8 0 8 7 ; 7 2 7 9] ;
% engine
[c,r] = find((A~=B).') ; % transpose to have indices ordered by row
r2 = r + rand(size(r)) ; % add offset for randomization
[r2,si] = sort(r2) ;
r2 = floor(r2) ;
c2 = c(si) ; % now the column indices are shuffled randomly within each row
[r c r2 c2] % show the randomization of column indices
% now put in values
C = A ;
C(sub2ind(size(C),r2,c2)) = A(sub2ind(size(C),r,c))
% result
[A B C]
Have fun
Jos
