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

2 ビュー (過去 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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by