Question

I am stuck at creating a matrix of a matrix (vector in this case)

What I have so far

index = zeros(size(A)) // This is some matrix but isn't important to the question
indexIndex = 1;
for rows=1:length(R) 
    for columns=1:length(K)       
        if(A(rows,columns)==x)
           V=[rows columns]; // I create a vector holding the row + column
           index(indexIndex) = V(1,2) // I want to store all these vectors
           indexIndex = indexIndex + 1
        end
    end
end

I have tried various ways of getting the information out of V (such as V(1:2)) but nothing seems to work correctly.

In other words, I'm trying to get an array of points.

Thanks in advance

Was it helpful?

Solution

I do not understand your question exactly. What is the size of A? What is x, K and R? But under some assumptions,

Using list

You could use a list

// Create some matrix A
A = zeros(8,8)

//initialize the list
index = list();

// Get the dimensions of A
rows = size(A,1);
cols = size(A,2);

x = 0;

for row=1:rows
    for col=1:cols     
        if(A(row,col)==x)
           // Create a vector holding row and col
           V=[row col]; 
           // Append it to list using $ (last index) + 1
           index($+1) = V 
        end
    end
end

Single indexed matrices

Another approach would be to make use of the fact an multi-dimensional matrix can also be indexed by a single value.

For instance create a random matrix named a:

-->a = rand(3,3)
a  =

0.6212882    0.5211472    0.0881335  
0.3454984    0.2870401    0.4498763  
0.7064868    0.6502795    0.7227253 

Access the first value:

-->a(1)
 ans  =

    0.6212882 

-->a(1,1)
 ans  =

    0.6212882  

Access the second value:

-->a(2)
 ans  =

    0.3454984  

-->a(2,1)
 ans  =

    0.3454984

So that proves how the single indexing works. Now to apply it to your problem and knocking out a for-loop.

// Create some matrix A
A = zeros(8,8)

//initialize the array of indices
index = [];

// Get the dimensions of A
rows = size(A,1);
cols = size(A,2);

x = 0;

for i=1:length(A)           
    if(A(i)==x)
        // Append it to list using $ (last index) + 1
        index($+1) = i; 
    end
end

Without for-loop

If you just need the values that adhere to a certain condition you could also do something like this

values = A(A==x);

Be carefull when comparing doubles, these are not always (un)equal when you expect.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top