# Variable Variation over the same range

6 views (last 30 days)
Davide Bertoldi on 23 Oct 2020
Commented: Steve Eddins on 27 Oct 2020
Hi everyone,
as a MatLab rookie I need your help! I´m working on a programm, where different variables shall assume certain values of a given range. I would like to achieve that these different variables assume values indipentently from each other even though the range is the same. This means, that I need to calculate all possible versions (i.e. where lam_o_p = 35, lam_i_p = 25 and lam_i_c = 40 or where lam_o_p = 30, lam_i_p = 30 and lam_i_c = 35).
%Span [m]
span=3.5:0.5:7;
%Number of lamellas [-]
lam=3:2:7;
%Depth outer lamella parallel to span [mm]
lam_o_p=20:5:50
%Depth inner lamella parallel to span [mm]
lam_i_p=20:5:50;
%Depth inner lamella cross to span [mm]
lam_i_c=20:5:50;
%Calculation of total depth [mm]
if(lam>5)
depth_tot_7=lam_o_p*4+lam_i_p*2+lam_i_c
else
0

Steve Eddins on 23 Oct 2020
I am interpreting your question this way: you would like to compute depth_tot_7 for all possible combinations of the different values of lam_o_p, lam_i_p, and lam_i_c.
Here are two different methods.
Using ndgrid
lam_o_p=20:5:50;
lam_i_p=20:5:50;
lam_i_c=20:5:50;
[LOP,LIP,LIC] = ndgrid(lam_o_p,lam_i_p,lam_i_c);
size(LOP)
ans =
7 7 7
% Calculate total depth for all possible combinations of LOP, LIP, and
% LIC.
depth_tot_7 = LOP*4 + LIP*2 + LIC;
size(depth_tot_7)
ans =
7 7 7
Using implicit expansion
This method requires less memory and is usually faster than the ndgrid method.
lam_o_p = 20:5:50; % row vector
lam_i_p = (20:5:50)'; % column vector
lam_i_c = reshape(20:5:50,1,1,[]); % vector along 3rd dimension
depth_tot_7 = lam_o_p*4 + lam_i_p*2 + lam_i_c;
size(depth_tot_7)
ans =
7 7 7
For more information on MATLAB behavior when performing arithmetic on operands with different sizes, see "Compatible Array Sizes for Basic Operations."
##### 2 CommentsShowHide 1 older comment
Steve Eddins on 27 Oct 2020
The question is still not perfectly clear to me, but perhaps you could create a function that would take lam as the input argument and return depth_tot. It might look something like this:
function depth_tot = my_fcn(lam)
%Depth outer lamella parallel to span [mm]
lam_o_p=20:5:50;
%Depth inner lamella parallel to span [mm]
lam_i_p=20:5:50;
%Depth inner lamella cross to span [mm]
lam_i_c=20:5:50;
%Calculation of total depth [mm]
if(lam>5)
depth_tot=lam_o_p*4+lam_i_p*2+lam_i_c
elseif (lam>3)
depth_tot=lam_o_p*2+lam_i_p*1+lam_i_c
else
depth_tot=lam_o_p*2+lam_i_c
end
Then you could call your function like this:
lam_range = 3:0.5:7;
for k = 1:length(lam_range)
D(k,:) = my_fcn(lam_range(k));
end