Choose elements, matrix with fewer elements
    9 visualizaciones (últimos 30 días)
  
       Mostrar comentarios más antiguos
    
Hi Everyone,
I have two matrices of unknown size and I wish to choose all the elements of the smaller matrix and 'n' random elements from the larger matrix, where 'n' is the length of the smaller matrix. I also do not want to reuse indices when doing the random selection. Could you please teach me how to do this most efficiently?
Thank you!
0 comentarios
Respuesta aceptada
  Doug Eastman
    
      
 el 17 de Jun. de 2011
        function y = myFun(a,b)
   aN = numel(a);
   bN = numel(b);
   % Make sure a is smaller
   if aN>bN
      temp = b;
      b = a;
      a = temp;
      temp = bN;
      bN = aN;
      aN = temp;
   end
   i = randperm(bN)';
   y = [a(:);b(i(1:aN))];
end
0 comentarios
Más respuestas (1)
  Walter Roberson
      
      
 el 17 de Jun. de 2011
        ael = numel(A);
bel = numel(B);
if ael < bel
  alen = length(A);
  ridx = randperm(1:bel);
  output = [A(:); reshape(B(ridx(1:alen)),[],1)];
elseif bel < ael
  blen = length(B);
  ridx = randperm(1:ael);
  output = [B(:); reshape(A(ridx(1:blen)),[],1)];
else
  error('Output not defined when arrays are same size');
end
Your task would be a little easier if you were not selecting according to the length of the smaller matrix, since matrix size is determined by the number of elements, not by the first non-unitary dimension (the definition of "length").
Perhaps you meant to write about vectors rather than about matrices? But if so then what if the vectors are different orientations?
Also, I was not able to figure out whether you wanted the smaller matrix to be shuffled or copied intact, and I couldn't tell if you wanted the outputs to be separate or combined sequentially or intra-shuffled.
0 comentarios
Ver también
Categorías
				Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!