To code based on percent in a matrix.
1 次查看(过去 30 天)
显示 更早的评论
a=[0 0 0 0 1 1 0 0; 0 0 0 0 0 0 0 0; 0 0 0 0 0 1 1 1; 1 0 0 0 0 0 0 0]
I need to replace zero value in a m x n matrix with value based on below function. For example, the matrix is as matrix a above. How can I code this problem to replace the matrix by values of this function? I just know the code to search zero values.
% code to search zero values
iszero=cellfun(@(p) isequal(p,0),dataShift);
% This function will randomly set a rules and save it in mxn matrix without disturbed the zero values
% case 1
% +----------------------+
% | Value | Percent |
% |11 | 0.5 |
% |22 | 0.3 |
% |33 | 0.175 |
% |44 | 0.025 |
% +----------------------+
% case 2
% +----------------------+
% | Value | Percent |
% |11 | 0.45 |
% |22 | 0.33 |
% |33 | 0.195 |
% |44 | 0.025 |
% +----------------------+
% case 3
% +----------------------+
% | Value | Percent |
% |11 | 0.40 |
% |22 | 0.36 |
% |33 | 0.215 |
% |44 | 0.025 |
% +----------------------+
update 4.29pm p.m'sia:
*algorithm required as below:
*1. In first row of matrix, case selected randomly is case 3. Therefore, in row 1, 40% zero values will assign as 11, 36% zero values will assign as 22, 21.5% zero values will assign as 33 and 2.5% zero values will assign as 44. The position in zero values available for 11, 22, 33 and 44, the selection will do randomly in that row.
2. Then, the next row will repeat process 1, but the case select is based on random.*
4 个评论
David Young
2012-1-6
That's clearer, thank you.
There's still a problem in knowing how to apply the probabilities. In row 1, there are 6 zeros. 40% of 6 is 2.4, 36% of 6 is 2.16, and so on. So exactly how many values should be set to 11, how many to 22 etc? Or do you want to set each zero element to a value chosen randomly from the distribution given (which would result in an unpredictable number of 11s in the row on any given run)?
It would help if you explain what the application is, or whether this is an exercise aimed at learning about programming.
Incidentally, your code that calls cellfun seems irrelevant. There are no cells involved in this task.
采纳的回答
Andrei Bobrov
2012-1-6
try this is code:
a=[0 0 0 0 1 1 0 0;
0 0 0 0 0 0 0 0;
0 0 0 0 0 1 1 1;
1 0 0 0 0 0 0 0];
cases = {[0.5 0.3 0.175 0.025],...
[ 0.45 0.33 0.195 0.025],...
[ 0.40 0.36 0.215 0.025]};
a2 = cellfun(@(x)cumsum([0 x]),cases,'un',0);
out = a;
for j1 = 1:size(a,1)
id = find(~a(j1,:));
n = numel(id);
[~,b] = histc(linspace(0,1-1e2*eps,n),a2{randi(3)});
b = b*11;
out(j1,id) = b(randperm(n));
end
0 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!