How to write a function with logical condition which takes an array and turns back an array?

What I want to acheive is the following. Let's say I have the function if and .
I have two vectors with nodes: x and y and I would like to calculate the function mentioned abose as an array. I can do it straightforwardly as
A = zeros(length(x), length(y));
for i = 1 : length(x)
for j = 1 : length(y)
if (x(i) ~= y(j))
A(i,j) = sin(alpha*(x(i) - y(j))) / (alpha * (x(i) - y(j)));
else
A(i,j) = 1;
end
end
end
This way is not really fast. I would like to have a function that will produce similar output as this cycle. More precisely, I would like to have the output in the form which is applicable for the trapz() command to calculate the double integral after all
trapz(y, trapz(x, K, 2))
there K has been calculated previously
I was trying something loke this
function val = K(alp, x, y)
% [x, y] = meshgrid(x, y); %% I was trying different variants here
% [x, y] = ndgrid(x, y);
if (x ~= y)
val = sin(alp * (x - y)) ./ ( alp * (x - y) );
else
val = 1;
end
end
but, of course, it did not work. Could you tell me, please, how shall I rewrite this function to achieve what I mentioned?

 Accepted Answer

K=sinc(alpha/pi*(x-y.'));

5 Comments

Thank you for the answer. In fact, I have a more fancy function that cannot be written as one function. Could you tell me please if the same structure can be rewritten in the form I used in my example? With the following logical construction:
if (x ~= y)
K = one story
else
K = another store
end
?
No, not without a loop. You could do
mask=(x=y.');
K=K1.* mask+K2.*(~mask);
Unfortunately, looks like it doesn't work even for the sinc() case (or, probably, I didn't get you correct). I considered
function val = Ker(x, y)
mask = (x == y.');
K1 = sin(pi * (x - y.')) ./ ( pi * (x - y.') );
K2 = 1;
val = K1.* mask + K2.*(~mask);
end
And runned
x = [1 : 1 : 5] / pi;
y = [3 : 1 : 7] / pi;
Ker(x, y)
The result was
1 1 NaN 1 1
1 1 1 NaN 1
1 1 1 1 NaN
1 1 1 1 1
1 1 1 1 1
I tried exchange them (val = K2.* mask + K1.*(~mask); ) and got
0.4546 0.8415 NaN 0.8415 0.4546
0.0470 0.4546 0.8415 NaN 0.8415
-0.1892 0.0470 0.4546 0.8415 NaN
-0.1918 -0.1892 0.0470 0.4546 0.8415
-0.0466 -0.1918 -0.1892 0.0470 0.4546
x = (1:5) / pi;
y = (3:7) / pi;
K = sin(pi * (x - y.')) ./ ( pi * (x - y.') );
K(x == y.')=1
K = 5×5
0.4546 0.8415 1.0000 0.8415 0.4546 0.0470 0.4546 0.8415 1.0000 0.8415 -0.1892 0.0470 0.4546 0.8415 1.0000 -0.1918 -0.1892 0.0470 0.4546 0.8415 -0.0466 -0.1918 -0.1892 0.0470 0.4546

Sign in to comment.

More Answers (0)

Products

Release

R2018a

Asked:

on 23 Oct 2021

Edited:

on 23 Oct 2021

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!