How to assign value from one matrix to another?

M=ones(14,2);
M(:,1)=1:14;
G=ones(20,2);
for o=1:20;
G(o,1)=ceil(14*rand);
G(o,2)=6.5*rand;
end
I want to assign values from matrix G to matrix M, with constraints that values from G(:,1) iteratively compare to those in M(:,1) and then assign value from the matching row to the second column. For example, if values in the first row of the matrix M are 1, 1, and if the values in the fifth row of the matrix G are 1, 5, i want to asign that value 5 to the first row, second column of the matrix M, which would then look like this: 1, 5.
I hope i wrote my problem understandable. Thank you for answers.
EDIT:
Now, for the first iteration, i want matrix A to look like this:
for second iteration like this:
and so forth. I need this because i want to do calculations for every iteration separately.

2 Comments

To make your question clear, post the expected result
i edited my question so you can see what the results should be. thank you

Sign in to comment.

 Accepted Answer

If I understood your example correctly, I'm not sure what's complicated. Simply use matrix comparison:
A = [(1:14)', ones(14,1)];
B = [randi(14, 20, 1), 6.5*rand(20,1)];
for brow = 1:size(B, 1)
A(A(:, 1) == B(brow, 1), 2) = B(brow, 2)
%do something with A
end
I've assumed that you wanted to keep around the changes from the previous iteration, unlike your example. If you don't want that make a copy of A inside the loop and change that.

3 Comments

well i'm a begginer in matlab so everything is complicated to me, and yes, i want to keep original values of matrix A after every iteration. I'll figure how to do that. I have another question if it's not too much. I need to subtract the value from B that replaces value from A, so does it change code much? Thank you for this answer @Guillaume
for brow - 1:size(B, 1)
Anew = A; %copy A and work on copy to keep original values
Anew(A(:, 1) == B(brow, 1), 2) = Anew(A(:, 1) == B(brow, 1), 2) - B(brow, 2); %subtract B value from corresponding Anew row
%do something with Anew
end
thank you a million times :D

Sign in to comment.

More Answers (0)

Products

Community Treasure Hunt

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

Start Hunting!