Multiple specific elements in an array

I have a matrix [a b c d e f g]. I want to sum [2*(a + b) + 3*(c+d) +4*(e+f)]. How do i go about doing this ?

답변 (1개)

Bhaskar R
Bhaskar R 2020년 2월 20일

1 개 추천

Assuming a, b,c, d, ..g are values in the vector say X
X = 1:7;
sum([2:4].*[sum(reshape(x(1:6), 2,3))]);

댓글 수: 5

rockstar49
rockstar49 2020년 2월 20일
Hi Bhaskar,
So far my code is:
clc
clear
values=input('Enter P(x)-Using [p1 p2 p3 etc] for uniform/nonuniform dist. \n');
x=[values]; User enters: '[.36 .14 .13 .12 .1 .09 .04 .02]'
y=-(values.*log2(x));
H=sum(y); %sum of all P(x) values to determine expected code length
fprintf('The average code length H(x) is: %d\n', H);
Now i want to sum 2*.36 + 3*(.14 + .13 +.12 +.1 +.09) +4*(.04 +.02)
Thank you for the input!
Zakir
Bhaskar R
Bhaskar R 2020년 2월 20일
Your question is different from your comment
"sum [2*(a + b) + 3*(c+d) +4*(e+f)]"
"Now i want to sum 2*.36 + 3*(.14 + .13 +.12 +.1 +.09) +4*(.04 +.02)"
rockstar49
rockstar49 2020년 2월 20일
Should I post it as another question ?
No, I mean to say that you have asked for "sum [2*(a + b) + 3*(c+d) +4*(e+f)]" then asking for "Now i want to sum 2*.36 + 3*(.14 + .13 +.12 +.1 +.09) +4*(.04 +.02)". Each time we can't change the evaluation of the statement. If there are only less than 10 entries you can write complete statement without using any commands using matlab indexing.
for this
sum 2*.36 + 3*(.14 + .13 +.12 +.1 +.09) +4*(.04 +.02) =
res = sum([2*x(1), 3*x(2:6), 4*x(7:8)]);
I think i am clear!
rockstar49
rockstar49 2020년 2월 20일
thank you! I did not know of this.
Best,
Zakir M

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

카테고리

도움말 센터File Exchange에서 Matrix Indexing에 대해 자세히 알아보기

질문:

2020년 2월 20일

댓글:

2020년 2월 20일

Community Treasure Hunt

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

Start Hunting!

Translated by