Checking a specific column in a matrix with a specific row,column in another matrix
Ältere Kommentare anzeigen
Greetings,
I want to check an (entire column) of B with a specific (row,column) in A and then extract values in B that are lower/higher than that value in A. For example; B(:,1) with A(1,1). I have already done this by creating a function file and calling it in my script.
My question now is how do I go from B(:,1) with A(1,1) to B(:,2) with A(2,2) without using this.
[Higher, Lower] = check(A(1,1), B(:,1))
[Higher1, Lower1] = check(A(1,2), B(:,2))
I want something that will automatically insert the desired matrix position. I'm asking this because my actual data set for matrices A = 30*12 and B = 62*12, thus making my method below inefficient. I have also included the expected results below.
clc; clear;
A = [1 2 1 2 5 2 1 2; 3 4 5 6 7 8 2 1];
B = [1 2;0 1; 2 4; 3 7; 0 5; 1 3; 2 4; 3 3; 9 8];
% Check B with A (I HAVE PROBLEM WITH THIS)
[Higher, Lower] = check(A(1,1), B(:,1))
[Higher1, Lower1] = check(A(1,2), B(:,2))
My function file:
function [Higher, Lower] = check(x,y)
% This function checks the y against x and extracts the respective higher/lower values.
% Set initial count to 0
con1 = 0;
count1 = 0;
for j = 1
for i = 1:9
if y(i) > x(j)
con1 = con1 + 1;
Higher(con1,j) = y(i);
end
end
con1 = 0;
end
for j = 1
for i = 1:9
if y(i) < x(j)
count1 = count1 + 1;
Lower(count1,j) = y(i);
end
end
count1 = 0;
end
end
Expected results:
Higher = [2;3;2;3;9]
Lower = [0;0]
Higher1 = [4;7;5;3;4;3;8]
Lower1 = [1]
All help is greatly appreciated. Thanks.
1 Kommentar
Guillaume
am 29 Mär. 2019
Jan has already shown how to write a much simpler check function and you should use that. However, even if you were going to use a loop as you have done, never hardcode the bounds of the loops. You wrote a function that accept a x of any size, yet your loop assumes that x is 9 elements. The whole point of functions is that they adapt to the input, so just changing
for i = 1:9
to
for i = 1:numel(x)
would mean that your current code would work regardless of the size of x (instead of erroring if x has less than 9 elements and producing the wrong result if it has more).
Also,
for j = 1
Well, that's absurd, it's the same as
j = 1;
Akzeptierte Antwort
Weitere Antworten (0)
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!