how to find sum different data for two different variables using loop in matlab

2 visualizzazioni (ultimi 30 giorni)
M.Rameswari Sudha il 28 Apr 2022
Commentato: Andy il 28 Apr 2022
I have different datas for two different variables (lambdai and b1). I need to find the separate M1 values and need to find sum M1 also. I couldn't find the answer. let me know if you will get the answer.
clc
clear all
lambdai=[0 5.6 22.4 57.4];
b1 = [100 80 120 90 70];
k=1
j=1;
l=1;
m=1;
for i=1:length(lambdai)
for s=1:length(b1)
M1=(b1(s).*lambdai(i))./lambda;
M(j,k)=M1;
j=j+1;
k=k+1;
end
end
sumM=sum(M)
4 CommentiMostra 2 commenti meno recentiNascondi 2 commenti meno recenti
M.Rameswari Sudha il 28 Apr 2022
yes. lamda = 100
Andy il 28 Apr 2022
Once I set a value for lambda it works, All the values for M1 are stored in the array M(. , . ) . sum(M) is calculated as expected but perhaps you want to sum all numbers in the array in which case it should be
sumM = sum(M , 'all');

Accedi per commentare.

Risposte (2)

Jan il 28 Apr 2022
Maybe you want to do: "Multiply each element of vector a with all elements of vector b, devide by 100 and get the sum of all results."
If you formulate the procedure clearly in naturla language, this is a good structure for the Matlab code also.
lambdai = [0 5.6 22.4 57.4];
b1 = [100 80 120 90 70];
lambda = 100;
M = zeros(length(lambdai), length(b1));
for i = 1:length(lambdai)
for s = 1:length(b1)
M(i, s) = b1(s) * lambdai(i) / lambda;
end
end
sumM = sum(M, 'all')
sumM = 392.8400
Of course you do not have to devide each element by lambda, because it is sufficient to divide the result only.
Matlab offers a way to do this without loops:
lambdai = [0 5.6 22.4 57.4];
b1 = [100 80 120 90 70];
lambda = 100;
M = lambdai.' * b1; % dyadic product: [4x1]*[1x5] = [4x5]
% Or:
% M = lambdai .* b1.'; % elementwise product: [1x4]*[5x1] = [5x4]
sumM = sum(M, 'all') / lambda
sumM = 392.8400
1 CommentoMostra -1 commenti meno recentiNascondi -1 commenti meno recenti
M.Rameswari Sudha il 28 Apr 2022

Accedi per commentare.

M.Rameswari Sudha il 28 Apr 2022
I got error using code as per you sent :
??? Error using ==> sum
Trailing string input must be 'double' or 'native'.
let me know the reason why I got error.
1 CommentoMostra -1 commenti meno recentiNascondi -1 commenti meno recenti
Jan il 28 Apr 2022
sum(X, 'all') was introduced in modern Matlab versions. For old versions use: sum(X(:)) instead.

Accedi per commentare.

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

R2009b

Community Treasure Hunt

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

Start Hunting!

Translated by