How can i store values calculated in my loop

7 次查看(过去 30 天)
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

采纳的回答

Star Strider
Star Strider 2019-3-20
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

更多回答(1 个)

Andrei Bobrov
Andrei Bobrov 2019-3-20
编辑:Andrei Bobrov 2019-3-20
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);

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

产品


版本

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by