Sum of a 4D matrix
Show older comments
Hey Guys!
I want to generate bunch of matrices in which each element takes value betwwn 0 and 1 and the summation of all elements in each matrix be less than or equal to one. I wrote the following code but it seems it takes forever.
Could someone please take a look at this code and let me know: 1) if the code is written correctly or not 2) Is it possible to rewrite the code in such a way that I have a faster one. Thanks in advance
K = 1;
nbrOfSubCarriers = 2*ones(1, K);
nt_L = 2;
nr_L = 2;
ulim=1; %max value of each element
llim=0; %min value of each element
sumlim=1; %max sum for each matrix
c = zeros(nr_L,nt_L, K, max(nbrOfSubCarriers(:)));
for k = 1 : K
for m = 1 : max(nbrOfSubCarriers(:))
RMat=rand(nr_L,nt_L)*(ulim-llim)+llim;
Rsum=sum(RMat(:));
Rcheck=Rsum>sumlim;
while any(Rcheck)
I=find(Rcheck);
RMat(I,:)=rand(length(I),nt_L)*(ulim-llim)+llim;
Rsum=sum(RMat(:));
Rcheck=Rsum>sumlim;
end
end
c(:,:,k,m) = RMat;
end
5 Comments
Walter Roberson
on 17 Apr 2019
You are doing sum over (:) of a 2D matrix. The (:) makes it a vector, so the sum() is going to be a scalar -- that is, the entire rand(nr_L, nt_L) matrix all together has to sum to less than or equal to 1. Rcheck is going to be a scalar, find() is going to be only 1, and you replace 1 row in RMat and try again.
I suspect you should be doing sum(Rmat,2) instead of sum(Rmat(:)) in order to look for rows that sum properly rather than lookingfor entire RMat that sum properly when you replace the first row over and over again.
Susan
on 17 Apr 2019
Susan
on 17 Apr 2019
Walter Roberson
on 17 Apr 2019
My tests suggest that the sum of N random variables is less than or equal to 1, 1/factorial(N) of the time. With you summing nr_L by nt_L all into one sum, then only 1/factorial(nr_L * nt_L) of the generated values will pass the test -- about 1/24 with the values or nr_L and nt_L that you use.
Perhaps it would be acceptable for your purpose to use
if Rsum <= sumlim
accept RMat as-is
else
Rmat = Rmat ./ Rsum; %makes the sum exactly 1
end
Susan
on 17 Apr 2019
Accepted Answer
More Answers (1)
Walter Roberson
on 17 Apr 2019
0 votes
4 Comments
John D'Errico
on 17 Apr 2019
Edited: John D'Errico
on 17 Apr 2019
randfixedsum does not apply to <= constraint, at least not without modification. That is not to say you could not use randfixedsum for ONE part of the solution.
Susan
on 17 Apr 2019
John D'Errico
on 17 Apr 2019
Let me see what I can write up.
Susan
on 17 Apr 2019
Categories
Find more on Resizing and Reshaping Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
