How to find a number location in a multiple sub-matrices?
2 次查看(过去 30 天)
显示 更早的评论
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?
0 个评论
采纳的回答
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});
0 个评论
更多回答(1 个)
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.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!