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

조회 수: 3 (최근 30일)
Filip Hansson
Filip Hansson 2022년 8월 15일
댓글: Image Analyst 2022년 8월 16일
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