Extract several rows from Matrix, Manipulate them in a Function and Re-Insert them at same position in Matrix
Show older comments
I would like to extract several rows of a Nx2 Matrix, manipulate them in a function, and then write the changed values back into the original matrix at the exact same positions.
For Example:
Given an 6x2 Matrix (M) such as the one below:
M=[1 2; 5 8; 6 9; 2 4; 1 7; 3 6] % Create 6x2 Matrix
M =
1 2
5 8
6 9
2 4
1 7
3 6
And a vector with N elements (N=6=number of rows of M) holding information of which rows of M belong to a sub-set (in this case you have two sub-sets: 1 and 2)
SubSets=[1 2 1 2 1 1]; % defines Sub-set memberships
SubSets=SubSets.'
SubSets =
1
2
1
2
1
1
I can now extract the rows of sub-set 1 from M with the following code:
Positions=logical(SubSets==1); % marks which rows in M are part of SubSet 1
Sub1Matrix=M(Positions,1:2)
Sub1Matrix =
1 2
6 9
1 7
3 6
Sub1Matrix is now manipulated by some (any) complex function (e.g. ChangeSubMatrix) that also uses variables from other parts of the script (e.g. a and b)and returns an "updated" matrix of same type and dimensions. For example:
a=1.978; % some constant stored as a scalar
b=[7 0 5 12]; % some other matrix in the script holding values
b=b.'; % transpose b
function [ChangedSubMatrix] = ChangeSubMatrix(Sub1Matrix, a, b)
% Some arbitratry function that changes the values of Sub1Matrix and returns these new values It really does not matter what exactly the manipulation is for the problem I am trying to solve in my question
ChangedSubMatrix=zeros(numel(Sub1Matrix)/2,2); % initializes matrix to hold changed elements of Sub1Matrix
ChangedSubMatrix(:,1)=Sub1Matrix(:,1).*a.*b./sin(deg2rad(Sub1Matrix(:,2))); % Some manipulation of 1st Column
ChangedSubMatrix(:,2)=Sub1Matrix(:,2).*a.*b./cos(deg2rad(Sub1Matrix(:,1))); % Some manipulation of 2nd Column
end
The Function is called below and the values in Sub1Matrix are updated
Sub1Matrix=ChangeSubMatrix(Sub1Matrix, a, b)
Sub1Matrix =
396.7392 27.6962
0 0
81.1525 69.2405
681.2307 142.6114
Ok, this is where I get stuck. How can I write back the new values (rows) of Sub1Matrix into M at the exact same positions where I had extracted the original rows from?
I want M to look like this afterwards:
M
M =
396.7392 27.6962
5.0000 8.0000
0 0
2.0000 4.0000
81.1525 69.2405
681.2307 142.6114
Any help would be much appreciated!
Accepted Answer
More Answers (0)
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!