How to creating 3 nested for loop to obtain 3d matrix?
4 views (last 30 days)
Show older comments
Yunus Emre TOMRUK
on 21 Dec 2018
Edited: Yunus Emre TOMRUK
on 21 Dec 2018
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
0 Comments
Accepted Answer
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
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!
More Answers (1)
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
1 Comment
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!