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!