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.

Community Treasure Hunt

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

Start Hunting!

Translated by