To code based on percent in a matrix.
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
David Young
am 6 Jan. 2012
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.
Akzeptierte Antwort
Andrei Bobrov
am 6 Jan. 2012
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 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Logical finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!