If statement in a for loop
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
MarshallSc
am 27 Aug. 2021
Beantwortet: Wan Ji
am 27 Aug. 2021
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 Kommentare
Akzeptierte Antwort
Chunru
am 27 Aug. 2021
Bearbeitet: Chunru
am 27 Aug. 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 Kommentare
Weitere Antworten (2)
KSSV
am 27 Aug. 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 Kommentare
Wan Ji
am 27 Aug. 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 Kommentare
Siehe auch
Kategorien
Mehr zu Matrices and Arrays finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!