Simplicity
Simplicity

Reputation: 48916

Index of elements

I have the following for-loop part of a function:

for i=1:5
for j=1:2
m=x(i)-c(j);
end
end

As a call to the function which includes the code above, I pass two values for c. Say the values passed are (3,5) for c1 and c2 respectively.

As you see in the for-loop above, I will have a two values for c, nanely, c(1) and c(2).

For the 3 and 5 values I have above, how can I assign them to c(1) and c(2) respectively?

When I did the following for instance:

c(1)=center1;
c(2)=center2;

where center1 and center2 represent the passed value to the function, I got the following error:

In an assignment  A(I) = B, the number of elements in B and I must be
the same.

Error in functionName (line 32)
    c(1)=center1;

Upvotes: 0

Views: 36

Answers (1)

horchler
horchler

Reputation: 18484

It looks like center1 is not a scalar. Print out the value or use isscalar to check it. This works:

c(1) = 1;

but this will not:

c(1) = [1 2];

Also, your double for loop makes no sense because you're overwriting the value of m on each iteration. Presumably you have more stuff inside it. However, you could just create a matrix m without any for loop at all using bsxfun:

x = rand(1,5);
c = rand(1,2);
m = bsxfun(@minus,x(:),c(:).')

This results in m being a 5-by-2 matrix. You can use bsxfun(@minus,x(:).',c(:)) if you prefer a 2-by-5 matrix.

Upvotes: 2

Related Questions