How to assign value from one matrix to another?

11 views (last 30 days)
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
Azzi Abdelmalek
Azzi Abdelmalek on 20 Aug 2015
To make your question clear, post the expected result
Drazen Tubic
Drazen Tubic on 20 Aug 2015
i edited my question so you can see what the results should be. thank you

Sign in to comment.

Accepted Answer

Guillaume
Guillaume on 20 Aug 2015
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
Guillaume
Guillaume on 20 Aug 2015
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

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!