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

1 次查看(过去 30 天)
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

采纳的回答

Image Analyst
Image Analyst 2022-8-15
You need to make m an array, not 60 separately named variables.
  2 个评论
Filip Hansson
Filip Hansson 2022-8-16
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 2022-8-16
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

请先登录,再进行评论。

更多回答(1 个)

David Hill
David Hill 2022-8-15
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

类别

Help CenterFile Exchange 中查找有关 Data Type Conversion 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by