How to properly compare tensors?
조회 수: 4 (최근 30일)
이전 댓글 표시
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!
댓글 수: 0
채택된 답변
Dyuman Joshi
2023년 7월 24일
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
Dyuman Joshi
2023년 7월 24일
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!
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Function Creation에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!