How to creating 3 nested for loop to obtain 3d matrix?

4 views (last 30 days)
Hi Everyone,
I am trying to run the following code and obtain a 3d matrix but i got following error.
"Subscript indices must either be real positive integers or logicals.
Error in coilsens (line 13)
B(z,alpha,beta) = z-y*tand(beta)+x*tand(alpha); "
How can i fix this problem?
Thanks.
clc
clear all
u0 = 4*pi*(10e-7);
y = 10e-3;
x = 10e-3;
B = zeros([11,31,31]);
for z = 2e-3:0.1e-3:3e-3
for alpha = 1:0.1:3
for beta = 1:0.1:3
B(z,alpha,beta) = z-y*tand(beta)+x*tand(alpha);
end
end
end

Accepted Answer

Andrei Bobrov
Andrei Bobrov on 21 Dec 2018
Edited: Andrei Bobrov on 21 Dec 2018
y = 10e-3;
x = 10e-3;
z = 2e-3:0.1e-3:3e-3;
alpha = 1:0.1:3;
beta = 1:0.1:3;
[zz,alp,bet] = ndgrid(z,alpha,beta);
B = zz-y*tand(bet)+x*tand(alp);
or
y = 10e-3;
x = 10e-3;
z = 2e-3:0.1e-3:3e-3;
alpha = 1:0.1:3;
beta = 1:0.1:3;
B = zz(:)-y*tand(reshape(bet,1,1,[]))+x*tand(alp(:)');
  3 Comments
Luna
Luna on 21 Dec 2018
@Andrei someone please teach me how to use this reshape function right on point everytime like he did!! geniusly avoid for loops amazing!
Yunus Emre TOMRUK
Yunus Emre TOMRUK on 21 Dec 2018
@Andrei Thank you for real quick and great response.

Sign in to comment.

More Answers (1)

madhan ravi
madhan ravi on 21 Dec 2018
clc
clear all
u0 = 4*pi*(10e-7);
y = 10e-3;
x = 10e-3;
z = 2e-3:0.1e-3:3e-3;
alpha = 1:0.1:3;
beta = 1:0.1:3;
B=zeros(numel(z),numel(alpha),numel(beta)); % preallocate
for z1=1:numel(z)
for alpha1 = 1:numel(alpha)
for beta1 = 1:numel(beta)
B(z1,alpha1,beta1) = z(z1)-y*tand(beta(beta1))+x*tand(alpha(alpha1));
end
end
end

Categories

Find more on Programming 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!