If statement in a for loop
1 回表示 (過去 30 日間)
古いコメントを表示
I have a 4*4 array, that each contains a 10*10 matrix. I want to assign a value to the components that are bigger than 1. I wrote the code below but the array still gives me the old answer. I my code correct?
for i=1:4
for j=1:4
for k=1:10
for r=1:10
if A{i,j}(k,r)> 1
A{i,j}(k,r)=0.25;
end
end
end
end
end
0 件のコメント
採用された回答
Chunru
2021 年 8 月 27 日
編集済み: Chunru
2021 年 8 月 27 日
There is no problem on your code.
% Generate some data
A0 = mat2cell(randn(40,40), [10 10 10 10], [10 10 10 10])
A = A0;
for i=1:4
for j=1:4
for k=1:10
for r=1:10
if A{i,j}(k,r)> 1
A{i,j}(k,r)=0.25;
end
end
end
end
end
A0{1,1}
A{1,1} % compare A0 and A1 to see the value of 0.2500
% However the code can be simplified.
A2 = cellfun(@changevalue, A0, 'UniformOutput', false);
A2{1,1}
% a local function
function x = changevalue( x)
x(x>1) = 0.25;
end
0 件のコメント
その他の回答 (2 件)
KSSV
2021 年 8 月 27 日
[m,n] = size(A) ;
iwant = cell(m,n);
for i = 1:m
for j = 1:n
T = A{i,j} ;
T(T>1) = 0.25 ;
iwant{i,j} = T ;
end
end
0 件のコメント
Wan Ji
2021 年 8 月 27 日
You can do like this
A = mat2cell(rand(40,40)+0.5, [10 10 10 10], [10 10 10 10]);
% A is your data randomly generated, you can put yours there
[i,j] = meshgrid((1:size(A,1)), (1:size(A,2)));
B = arrayfun(@(i,j)A{i,j}-A{i,j}.*(A{i,j}>1) + 0.25*(A{i,j}>1), i, j, 'uniform',0); % B is what you want
Or you can do like this
A = cell2mat(A);
A(A>1) = 0.25;
A = mat2cell(A,10*ones(4,1),10*ones(4,1)); % the final is what you want
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Matrices and Arrays についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!