If statement in a for loop
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponse acceptée
Chunru
le 27 Août 2021
Modifié(e) : Chunru
le 27 Août 2021
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 commentaires
Plus de réponses (2)
KSSV
le 27 Août 2021
[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 commentaires
Wan Ji
le 27 Août 2021
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 commentaires
Voir également
Catégories
En savoir plus sur Matrices and Arrays dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!