If statement for 2 different variables.

I have an equation:
x = [10 / pi + j / sin(i-1)] * cos[j * (i-1) * pi]
where i = 2 to 6 and j = 1 to 7. I am trying to make a code with both i and j. I am solving this equation for all combinations. For example, I want to solve the equation when i = 2 and j = 1, 2, ..., 7. And when i = 3, j = 1, 2, ..., 7. The end result should also be put in a matrix i by j = 5 by 7.
Thank you to all that reply!

3 comentarios

Dyuman Joshi
Dyuman Joshi el 22 de Sept. de 2023
Look into the 1st example provided in the documentation of for loop
Kavi Patel
Kavi Patel el 22 de Sept. de 2023
How did I not see this, thank you so much!
Star Strider
Star Strider el 22 de Sept. de 2023
A loop is actually not necessary. See my Answer.

Iniciar sesión para comentar.

Respuestas (1)

Try this —
x = @(i,j) (10 / pi + j ./ sin(i-1)) .* cos(j .* (i-1) * pi);
i = 2:6;
j = 1:7;
[I,J] = ndgrid(i,j);
Iv = I(:);
Jv = J(:);
Xv = x(Iv,Jv);
X = x(I,J) % Matrix
X = 5×7
-4.3715 5.5599 -6.7483 7.9367 -9.1251 10.3135 -11.5019 4.2828 5.3826 6.4823 7.5821 8.6818 9.7816 10.8814 -10.2693 17.3554 -24.4416 31.5278 -38.6139 45.7001 -52.7863 1.8618 0.5404 -0.7809 -2.1023 -3.4236 -4.7450 -6.0663 -2.1403 1.0974 -0.0546 -0.9882 2.0311 -3.0739 4.1167
figure
surf(I,J,X) % Surface Plot
grid on
colormap(turbo)
xlabel('i')
ylabel('j')
zlabel('x(i,j)')
ResultVectors = table(Iv,Jv,Xv) % Table Of Vectors
ResultVectors = 35×3 table
Iv Jv Xv __ __ _________ 2 1 -4.3715 3 1 4.2828 4 1 -10.269 5 1 1.8618 6 1 -2.1403 2 2 5.5599 3 2 5.3826 4 2 17.355 5 2 0.5404 6 2 1.0974 2 3 -6.7483 3 3 6.4823 4 3 -24.442 5 3 -0.78095 6 3 -0.054593 2 4 7.9367
.

Categorías

Productos

Versión

R2023a

Preguntada:

el 22 de Sept. de 2023

Comentada:

el 22 de Sept. de 2023

Community Treasure Hunt

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

Start Hunting!

Translated by