Only applying a "for" command on half of the matrices in it

3 views (last 30 days)
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

Accepted Answer

Image Analyst
Image Analyst on 15 Aug 2022
You need to make m an array, not 60 separately named variables.
  2 Comments
Filip Hansson
Filip Hansson on 16 Aug 2022
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?
Image Analyst
Image Analyst on 16 Aug 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

Sign in to comment.

More Answers (1)

David Hill
David Hill on 15 Aug 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

Categories

Find more on Data Type Conversion 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!