Help needed with matrix in for-loop and output of matrix
2 views (last 30 days)
Show older comments
Hi, i have a question regarding some tasks to change the content of a matrix. The goal of this operation is to 'clear' a matrix consisting out of 2 columns and a random amount of rows. The operation has to be done using a function-file. The input has to be x = [:,1] and y = [:,2]. After that the first step is to put them together in a matrix A = [x,y] and the rows need to be sorted from lowest to highest value from the first column, B = sortrows(A,1). The problem however is that in the first column the x-values are supposed to be unique with it's matching y-values (2nd column).
So let's say you got a x = [1;3;4;3;2;2;4] and y = [5;1;3;2;9;6;1] which will then transfer into the matrix B = [1,5;2,9;2,6;3,1;3,2;4,3;4,1]. Now as you can see there are several x-values that aren't unique in the first column. The result of this operation should be the next matrix C = [1,5;2,6;3,1;4,1].
- If an x-value is unique, then it's y-value is the one to be taking.
- If an x-value is not unique, then the y-value should be the lowest value matching with these x-values.
How can i write a code into a for-loop(?) with these 2 conditions so it can be used for any matrix with n x 2 dimension? This is what i had so far, yet i have no idea if this is anywhere near the solution..
function [ new_matrix ] = matrix( x,y )
A = [x,y];
B = sortrows(A,1);
n = size(B,1);
for i = 1:1:n
if B(i,1) == B(i+1,1) && B(i,2) <= B(i+1,2)
B(i+1,:) = [];
elseif B(i,1) == B(i+1,1) && B(i,2) >= B(i+1,2)
B(i,:) = [];
end
end
This is an example of how it's supposed to work, but for any matrix with n x 2 dimensions.
%
0 Comments
Accepted Answer
Sara
on 23 Dec 2014
With x,y column vectors:
A = [x,y];
B = sortrows(A,1);
unique_x = unique(B(:,1));
new_matrix = zeros(numel(unique_x),2);
new_matrix(:,1) = unique_x;
for i = 1:numel(unique_x)
k = find(B(:,1) == unique_x(i));
new_matrix(i,2) = min(B(k,2));
end
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements 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!