How to find a number location in a multiple sub-matrices?

조회 수: 1 (최근 30일)
Moe
Moe 2015년 6월 17일
답변: Walter Roberson 2015년 6월 17일
I have a combined matric "z" which is included 3 sub-matrices "a", "b" and "c". RNG is a random number from matrix z. So, I want to know that this RNG is belongs to which sub-matrices?
a = [2;3;4;5];
b = [6;7;9;10;23];
c = [56;32];
z = [a;b;c];
rand = randperm(size(z,1));
RNG = z(rand(1),:);
RNG = % belong to which sub-matrices?

채택된 답변

Walter Roberson
Walter Roberson 2015년 6월 17일
[tf, idx] = ismember(RNG, z);
[count, binnum] = histc(idx, cumsum([1, length(a), length(b), length(c)]);
varnames = {'a', 'b', 'c'};
fprintf('value %d came from matrix %s\n', RNG, varnames{binnum});

추가 답변 (1개)

Geoff Hayes
Geoff Hayes 2015년 6월 17일
Mohammad - rand is the name of a built-in MATLAB function so you shouldn't be using it as the name of a local variable. As for which sub-matrix does the RNG value belong to, you can just use the index into z to determine that. For example, if
z = [a;b;c];
randValues = randperm(size(z,1));
RNG = z(randValues(1),:);
then the index into z is
randIndex = randValues(1);
Now if we consider the number of elements of each sub-matrix, then we can determine the upper bound on each sub-matrix with respect to the index into z as follows
subMatricesIdcsUpperBounds = cumsum([length(a) length(b) length(c)]);
which is
subMatricesIdcsUpperBounds =
4 9 11
We can interpret the above as a corresponding to indices 1 through 4 into z, b corresponding to indices 5 through 9 of z, and c corresponding to indices 10 through 11 of z.
Then we just do
find(randIndex <= subMatricesIdcsUpperBounds,1)
which returns an index k which tells us that RNG can be found in the kth sub-matrix.

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by