MATLAB MatLab Matrix Help: Integrating for Entries Equal to 1

  • Thread starter Thread starter Apteronotus
  • Start date Start date
  • Tags Tags
    Matlab Matrix
AI Thread Summary
In MATLAB, to assign values in matrix A based on entries in matrix B equal to 1, the recommended approach is to use the integral function instead of the deprecated quad function. The proposed syntax A(B==1) = quad(@(x) x, 0, C(B==1)) fails because the limits of integration must be scalars. A potential solution is to utilize the ARRAYFUN function, which can apply a function to each element of an array. However, it's important to verify that the function being used is vectorized, as not all functions automatically support this. This method avoids the need for nested loops while ensuring proper integration limits.
Apteronotus
Messages
201
Reaction score
0
Hi,

I have a quick question regarding MatLab.

I have 3 matracies A, B and C.

For every entry equal to 1 in B, I want to let the corresponding entry in A be an integral of x from 0 to C.

ex.
for all (i,j)
if B(i,j)==1 then let A(i,j)=quad(@(x) x, 0, C(i,j))

A quick way to do this for large matracies I thought was to use the following syntax:
A(B==1) = quad(@(x) x, 0, C(B==1))

But get the following error:
? Error using ==> quad at 70
The limits of integration must be scalars.

Is there any way around this other than a "for i, for j" statement?

Thanks,
 
Physics news on Phys.org
I haven't tried it, but ARRAYFUN may be what OP is looking for.

https://www.mathworks.com/help/matlab/ref/arrayfun.html
But just a general comment, don't assume a function is automatically vectorized unless the documentation explicitly says it is.
 
Back
Top