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

조회 수: 2 (최근 30일)
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
M
M 2017년 11월 6일
What error do you get ?
How are the others variables defined ? (b,noise,Ncarrier)
Robert
Robert 2017년 11월 6일
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?

댓글을 달려면 로그인하십시오.

답변 (2개)

KL
KL 2017년 11월 6일
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 2017년 11월 9일
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.

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by