How can i store values calculated in my loop

9 views (last 30 days)
Here is my code, i managed to do the operation however i can't store each column, what i get is only result of latest column, In this code, first element of column is checked if its less than 10, if yes then element is replaced by zero, code will keep checking elements of column and replace them by zero until it reaches to number 10;
However; I can't store all the columns, only last column is stored, how can store all the columns that i can reconstruct the new matrix;
X1 is the new matrix
X = [9 20 15 9 10 5;5 20 5 20 15 3;15 29 39 49 5 10];
[rows columns depth]=size(X);
for r=1:columns; % search for each column
X1=X(:,r); %X1 is going to be new matrix
for k=1:3 %k will help me to go through each element in column
if X1(k)<10 % if first element is less than 10, replace it by 0 till
% i find the number which equal or higher than 10
X1(k)=0;
else
break % if number is already more than 10, don't search for other
% element in the column, switch to next column
end
end
end

Accepted Answer

Star Strider
Star Strider on 20 Mar 2019
I am not certain what you are doing. One option is to create a second matrix (‘X2’ here), and store the results in it:
X = [9 20 15 9 10 5;5 20 5 20 15 3;15 29 39 49 5 10];
[rows columns depth]=size(X);
X2 = zeros(size(X));
for r=1:columns;
X1=X(:,r);
for k=1:3
if X1(k)<10
X1(k)=0;
else
break
end
end
X2(:,r) = X1;
end
producing:
X2 =
0 20 15 0 10 0
0 20 5 20 15 0
15 29 39 49 5 10

More Answers (1)

Andrei Bobrov
Andrei Bobrov on 20 Mar 2019
Edited: Andrei Bobrov on 20 Mar 2019
X = [9 20 15 9 10 5;5 20 5 20 15 3;15 29 39 49 5 10];
[rows, columns]=size(X);
for r=1:columns
for k=1:3
if X(k,r)<10
X(k,r)=0;
else
break
end
end
end
or without loops:
X = X.*(cumsum(X >= 10) > 0);

Products


Release

R2018b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!