How to properly compare tensors?

2 views (last 30 days)
Hi! I have the following function:
function toint = toint(p, r, R, dRdt, mu)
c = 29979245800; %cm/s
gamma = 1/sqrt(2*(1 - (dRdt/c).^2));
limitmin = R - deltR(R, dRdt);
limitmax = R;
minsize = size(limitmin)
maxsize = size(limitmax)
if (r > limitmin) & (r < limitmax)
toint = r.^2./((gamma.^(p-1)).*(1-getbetastar(dRdt/c).*mu).^((p+3)/2))
else
toint = 0
end
end
where r, R and limitmin are all 3D tensors. Now, I know they have the same size and the condition doesn't result with an error. But instead of getting a 3D tensor as the result of this function, I just get the one dimensional zero. This leads me to believe that the if condition checks if all corresponding elements of the tensors follow the condition - I don't want that, I want to get a 3D tensor containing values of zero/the value it calculated for the exprassion. What should I do? Thank you in advance!

Accepted Answer

Dyuman Joshi
Dyuman Joshi on 24 Jul 2023
Use logical indexing.
function toint = toint(p, r, R, dRdt, mu)
c = 29979245800; %cm/s
gamma = 1/sqrt(2*(1 - (dRdt/c).^2));
limitmin = R - deltR(R, dRdt);
limitmax = R;
minsize = size(limitmin)
maxsize = size(limitmax)
%Preallocate the array toint as zeros, so that you only have to assign
%values to indices corresponding to the condition
toint = zeros(size(r));
%Indices corresponding to the condition
idx = (r > limitmin) & (r < limitmax);
%Assuming r is the only non-scalar array here, and rest of the variables are scalars
%If any other variables are non-scalar, use the index idx for them as well
toint = r(idx).^2./((gamma.^(p-1)).*(1-getbetastar(dRdt/c).*mu).^((p+3)/2));
end
  2 Comments
Noya Linder
Noya Linder on 24 Jul 2023
The result is a vector and not a tensor, but just specifiying toint(idx) = ... in the last line of your answer fixes that right up. Thank you so much! Have a great morning/evening/whatever it is wherever you are
Dyuman Joshi
Dyuman Joshi on 24 Jul 2023
Yes, you are correct. Idk how I missed it, it must be the time for my evening coffee haha.
Have a good day as well!

Sign in to comment.

More Answers (0)

Categories

Find more on Genomics and Next Generation Sequencing 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!