Reputation: 7
I have a code that should do exactly this:
A = [2;3;4;5;6;7];
b = 2;
B(10).b = zeros(6,1);
for i = 1:10
C = A;
B(i).b = C.*(b^i);
if i>1
if B(i).b(1,1)-B(i-1).b(1,1)>50
C(7) = b;
end
end
end
The problem is that in every iteration C matrix is replaced with the values in matrix A. This is simplified version of my code, but the essence is here, and the code should do exactly this, at some point if a criteria is met, add another row to matrix C and continue executing the code with that row in matrix C. Is it possible to do that? I'd appreciate ideas very much. Thank you.
Upvotes: 0
Views: 390
Reputation: 1109
You can append b to C and overwrite the value of C with the newly created value:
if i>1
if B(i).b(1,1)-B(i-1).b(1,1)>50
C = [C; b];
end
end
This should work just fine as long as C & b are not too large.
Upvotes: 1
Reputation: 124
It is not recommended to change the matrix size during execution because you loose runtime. The best solution is to estimate the size of the matrix at the very beginning.
If there is no other possibility, you can add a row by the following code:
A = [1 2; 3 4];
A = vertcat(A,[2 3]);
The same works also for columns:
A = [1 2; 3 4];
A = horzcat(A,[2; 3]);
To take away a row, just write (here for row 2):
A(2,:) = [];
The same works with columns:
A(:,2) = [];
To change only selective parts of a matrix, the following can be done (some examples):
A(1:2,1) = [2 3]; % change row
A(1,1:2) = [2;3]; % change column
A(2,1) = 5; % change single cell
This is exactly what Rashid does with the statement C(1:6) = A;. Because it is only a column vector, the indices refer to the columns. It is equivalent to C(1,1:6)=A;
Then it is only a question of implementation to put around an if-statement with your desired condition.
Best regards
Upvotes: 0