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!