Randomizing the picking and changing of values in a 3D array

I have a 24x365x60 array and would like to set 4 of the 24 values for each of the 365 columns to a constant (11), based on a 24x365 matrix with "1"s in the particular positions, for a randomized 30 of the 60 sheets (third dimemsion) and letting the other 30 beeing unchanged. What is the best way to solve this?

 Accepted Answer

x = zeros(24, 365, 60);
m3 = randperm(60, 30);
for i3 = m3
for i2 = 1:365
m1 = randperm(24, 4);
x(m1, i2, i3) = 11;
end
end
sum(x(:) == 11)
ans = 43800
Is this the wanted number of 11's? 4*365*30 = 43800

8 Comments

Thank you! Yes, 11 is the wanted number. I have a 24x365 matrix of zeros and ones (Matrix A), 4 ones in each column and 20 zeros. The posistions of the ones in Matrix A is the positions i would like the 11s to have in each of the 30 sheets. How are one to modify the "m3 = randperm(24, 4); " code to make that happen?
I'm not sure, what "the 11s to have in each of the 30 sheets" exactly means.
Sorry! What I meant was that I only want this change to apply for 30 out of the 60 sheets. The Matrix A has 24 rows with "1"s located in 4 of those positions. I would like the same positions in the 24x365x60 matrix to be replaced with the number 11 while the others are unchanged, for 30 of the sheets. The remaining 30 sheets should be unchanged aswell.
Right now I have come up with this instead, is there any way to apply "a3" so the "for" applys for only when "a3" is active?
AntalObjekt = 60;
Procent = 0.5;
AntalLadd = fix(AntalObjekt*Procent);
b3 = 1:AntalObjekt;
a3 = randsample(b3, AntalLadd);
i = 11;
m_spotpris=repmat(m_spotpris, 1, 1, AntalObjekt); % Makes it a 24x365x60 matrix
for i = i
AllaMatriser(m_spotpris==1) = i; %A AllaMatriser is a 24x365x60 matrix
end
@Filip Hansson: "The remaining 30 sheets should be unchanged aswell."
But this is done by the code of my answer already. There was a confusin typo only and I've remaned the inner "m3" to "m1".
Yes but I would like the "11"s in fixed positions and therefore not by using "randperm(24, 4)" but rather some code that will locate the ones in "m_spotpris" and then replace this specific positions in "AllaMatriser" with "11"s. This positions have both x and y coordinates and therfore, maybe, I have to change "i2" aswell?
You want to replace randperm(24, 4)? Okay then simply replace this command in my code.
A short example would clarify, what you want to do exactly.
I saw the solution from you in another tread and it worked lika a charm!

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Asked:

on 16 Aug 2022

Commented:

on 18 Aug 2022

Community Treasure Hunt

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

Start Hunting!