user3685062
user3685062

Reputation: 79

applying a function for cell elements in MATLAB

I have neighh1 that is 1 by 10 cell

neighh1 =

Columns 1 through 6

[5x1 double]    [3x1 double]    [3x1 double]    [7x1 double]    [4x1 double]    [5x1 double]

Columns 7 through 10

[4x1 double]    [4x1 double]    [3x1 double]    [4x1 double]

I want to take two cells of neighh1 , for example neighh1{1} & neighh1{3}

neighh1{1}=

2 4 7 8 10

neighh1{3}=

5 6 9

I have the matrix N that is a 2-dimentional array that contains 0 & 1, Then I want to check if N(i,j) == 1 or not . Where i & j are the elements of neighh1{1} & neighh1{3} so if N(4,7)== 1 I want to save 4 & 7 in a new matrix

Upvotes: 0

Views: 120

Answers (4)

Dennis Jaheruddin
Dennis Jaheruddin

Reputation: 21563

Based on your comments you are simply looking for a way to access the contents of a cell.

I think you are looking for something like this:

for t=1:numel(neighh1{1})
  for k = 1:numel(neigh1{3})
    N(neighh1{1}(t),neigh1{3}(k))
  end
end

If you want to add the values to a matrix directly in the loop, you could do this:

M=[];
for t=1:numel(neighh1{1})
  for k = 1:numel(neigh1{3})
      x = neighh1{1}(t);
      y = neigh1{3}(k);
    if N(x,y)
      M(end+1,:) = [x y];
    end
  end
end

Upvotes: 1

Stewie Griffin
Stewie Griffin

Reputation: 14939

A = {[1:4].',[1:3].',[4:7].',[1:7].'}
A = 
    [4x1 double]    [3x1 double]    [4x1 double]    [7x1 double]

To execute a function on all elements, you can use cellfun straight forward like this:

B = cellfun(@sin, A, 'uni', 0);

You can after this use the cells you want using regular indexing.

If you really want to execute a function only on cells 2 and 3, you may do:

B = cellfun(@sin, A([2, 3]), 'uni', 0);

Upvotes: 0

Nras
Nras

Reputation: 4311

Well this is possible, easiest if you wanted to apply it for all elements, though. The trick is, you use a subset of that cell and apply the function to all elements of that via cellfun

cellfun(@length, neighh([1, 3]))

It returns the Vector [5, 3].

Upvotes: 0

Luis Mendo
Luis Mendo

Reputation: 112659

If you want to index N with all combinations of the two vectors contained in the two cells:

[ii jj] = ndgrid(neighh1{1}, neighh1{3}.')
result = N(sub2ind(size(N), ii,jj));

See ndgrid and sub2ind for reference.

Upvotes: 1

Related Questions