Only applying a "for" command on half of the matrices in it
3 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Filip Hansson
il 15 Ago 2022
Commentato: Image Analyst
il 16 Ago 2022
I have a "for" command that makes certain elements in about 60 matrices to a constant. I would like to make it so every time I run the script the "for" only selects a random 30 matrices to make that change and for the ramaining 30 to be left unchanged. How is this possible??
The code at the moment:
for i = 11
m_a(m_spotpris==1) = i;
m_b(m_spotpris==1) = i;
m_c(m_spotpris==1) = i;
m_d(m_spotpris==1) = i;
.
.
.
% And so on
0 Commenti
Risposta accettata
Image Analyst
il 15 Ago 2022
You need to make m an array, not 60 separately named variables.
2 Commenti
Image Analyst
il 16 Ago 2022
Did you try a simple for loop:
% Thank you! I have done this and is now stuck with the same problem.
% I have a 24x364x60 array and would like to set 4 of those 24 values to 11,
% based on another matrix with "1"s in those particular positions,
% for 30 randomized of those 60 arrays. How is this possible?
% Assign sample data.
array3d = randi(99, 24, 364, 60);
[rows, columns, slices] = size(array3d)
refMatrix = randi([0, 2], 364, 60);
% Get 4 randomly chosen rows.
rowsToChange = sort(randperm(rows, 4))
% Replace array3d where refMatrix is 1.
for k = 1 : length(rowsToChange)
thisRow = rowsToChange(k);
for col = 1 : columns
for slice = 1 : slices
if refMatrix(col, slice) == 1
array3d(thisRow, col, slice) = 11;
end
end
end
end
Più risposte (1)
David Hill
il 15 Ago 2022
m=randi(10,10,10,60);%generate your matrix (should store as 3-D matrix)
r=randperm(60,30);%generate the 30 affected matrices
for k=1:length(r)
M=m(:,:,r(k));%establish temp matrix
M(M==1)=99;%change all of the 30 affected matrices where elements equal 1 to 99
m(:,:,r(k))=M;
end
0 Commenti
Vedere anche
Categorie
Scopri di più su Data Type Conversion in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!