Making use of indexes and meshgrids

19 views (last 30 days)
Helen
Helen on 23 Aug 2014
Edited: Guillaume on 24 Aug 2014
Let's say I have two vectors ( Elem and Dren ). Each row in Dren represents a sum of a possible combination of elements from Elem . ID is an array that has the same number of rows as Dren and stores the indexes of Elem that correspond to every row in Dren .
Example:
Elem = [3 2 6];
Dren = [3; 2; 6; 5; 9; 8; 11];
ID = [ 1 0 0;
2 0 0;
3 0 0;
1 2 0;
1 3 0;
2 3 0;
1 2 3];
Then I used a meshgrid for Elem and Dren to get all possible pairs of these values and created a new array ( R ) with their ratios, as shown below:
[E,D]=meshgrid(Elem,Dren);
for line=1:size(E,1)
for col=1:size(E,2)
R(line,col)=D(line,col)./E(line,col);
end
end
This gives me:
R =
1.0000e+000 1.5000e+000 5.0000e-001
6.6667e-001 1.0000e+000 3.3333e-001
2.0000e+000 3.0000e+000 1.0000e+000
1.6667e+000 2.5000e+000 8.3333e-001
3.0000e+000 4.5000e+000 1.5000e+000
2.6667e+000 4.0000e+000 1.3333e+000
3.6667e+000 5.5000e+000 1.8333e+000
I have filtered the results of R and selected the ones that are lower than 6, so I get:
R(find(R<6)) =
1.0000e+000
6.6667e-001
2.0000e+000
1.6667e+000
3.0000e+000
2.6667e+000
3.6667e+000
1.5000e+000
1.0000e+000
3.0000e+000
2.5000e+000
4.5000e+000
4.0000e+000
5.5000e+000
5.0000e-001
3.3333e-001
1.0000e+000
8.3333e-001
1.5000e+000
1.3333e+000
1.8333e+000
Now I would like to create a new array that will store these filtered values in the first column and show the row values from ID equivalent to them. In other words, the first column would be R(find(R<6) and the other columns would be the Elem indexes related to the Dren value used in every R calculation. Since I used the find function in R, I don't know how to associate the correct ID rows.
For example, for R6(1,1)= 1.0000e+000, we know it was calculated from D(1,1)=3, so the corresponding ID row is [ 1 0 0]. The first row of the array would therefore be:
Store(1,:) = [ 1.0000e+000 1 0 0 ]
How can I do this for all the elements in R6?

Accepted Answer

Guillaume
Guillaume on 24 Aug 2014
Edited: Guillaume on 24 Aug 2014
First of all, you don't need the loops to calculate R:
R = D ./ E;
will work just as well.
To get what you want, use the two outputs (row, column) version of find:
R6=R(find(R<6));
[Drow, ~] = find(R<6); %Drow is the row from D, Dren, ID where the element in R6 comes from
store = [R6 ID(Drow, :)];
As you do want the two outputs version of find but don't care about the second output, I just use the ~ symbol for the second output (which means don't care).

More Answers (0)

Categories

Find more on Matrices and Arrays 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!