How to change a matrixvalue dependent on the previous matrixvalue?
1 view (last 30 days)
Show older comments
Hellow
I made this code including for loops but this is very time consuming. My goal is that in the T1 matrix a 1 in placed when the value of matrix T changes from 0 to 1 when looking down in the collum. When the next value of T is again a 1 the T1 matrix must give a 0. So I want to count the number of times the matrix value of T changes from 0 to 1. Has anyone a quicker alternative then this?
for ii=1:4; for jj=1:9 if T(jj+1,ii)>0 && T(jj,ii)<T(jj+1,ii); T1(jj,ii)=1; end end end
Many thanks in advance!
Accepted Answer
Akira Agata
on 20 Feb 2017
I think the following code should be alternative.
idx = [(T(2:end,:) > 0) & (T(1:end-1,:) < T(2:end,:)); logical(zeros(1,size(T,2)))]
T1(idx) = 1;
Let me check whether it works correctly by following.
T = randi([0 1], 10, 4); % Randomly generated 0/1 array
T1 = zeros(size(T));
T2 = zeros(size(T));
% Original code
for ii=1:4;
for jj=1:9
if T(jj+1,ii)>0 && T(jj,ii)<T(jj+1,ii);
T1(jj,ii)=1;
end
end
end
% Proposed code
idx = [(T(2:end,:) > 0) & (T(1:end-1,:) < T(2:end,:)); logical(zeros(1,size(T,2)))]
T2(idx) = 1;
The result isequal(T1,T2) becomes true.
I hope this answer will help you.
0 Comments
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!