how to include n = 1:25; power = 1:4:100; cg = 1:6:150; in single expression using for loop

2 views (last 30 days)
i have initialized
n=1:25(number of users)
power = 1:4:100(power values of different users)
cg = 1:6:150(channel gain for different users)
i need to make use of all three variables in the same expression
sum_n = (b*log(1+((power*cg)/noise))*Ncarrier)
followed by for loop i facing error while executing pls help me to solve this issue.
  2 Comments
M
M on 6 Nov 2017
What error do you get ?
How are the others variables defined ? (b,noise,Ncarrier)
Robert
Robert on 6 Nov 2017
Your question is unclear. What are the variables b, noise, and Ncarrier?
As a start, the answer is probably one of the following:
1) Loop over the common length
for index = 1:length(n) % should be same as length(power0 and length(cg)
% use n(ii), power(ii), and cg(ii)
end
2) Use nested for-loops (could also be done with indices in for loops):
for i_n = n
for i_power = power
for i_cg = cg
% ...
end
end
end
3) Use meshgrid
[N, POWER, CG] = meshgrid(n, power, cg);
% ...
4) Use singleton expansion (or bsxfun if you are using a version of MATLAB before R2016b)
n = 1:25; % first dimension
power = (1:4:100)'; % second dimension
cg = reshape(1:6:150, 1, 1, []); % third dimension
% ...
Will these arrays always have the same length? Are you trying to execute your expression for every possible combination of these values? Do you need to collect the results in an array?

Sign in to comment.

Answers (2)

KL
KL on 6 Nov 2017
Do you really need a for loop? Check this,
n = 1:25;
power = 1:4:100;
cg = 1:6:150;
b=1;
noise = rand(size(n));
Ncarrier = 1;
sum_n = (b.*log(1+((power.*cg)./noise)).*Ncarrier)
.* means element-wise multiplication.

Eric
Eric on 9 Nov 2017
Since all your vectors are the same length, you probably want to be using the binary operators in your equation, which includes a period before operators that can be used on matrices, for example: .* .^ and ./
sum_n = (b.*log(1+((power.*cg)./noise)).*Ncarrier);
This will ensure that your sum_n will also be 25 elements long (or error if the vectors don't match), and assumes b, noise and Ncarrier are either all scalars or also vectors of the same length as n, power, and cg (i.e. 25).
Protip: MATLAB has a built in function, log1p, which computes log(1+x) more accurately for small values of x.

Categories

Find more on Matrices and Arrays 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!