How can I solve this matrix question using for loop?
조회 수: 3 (최근 30일)
이전 댓글 표시
Dear all,
There is a problem that I need to solve in the attached picture. First I defined the benefit matrix as A, and then I set up a for loop and tried to find the newly formed benefit matrices in the tables for each user from 1 unit of water to 8 units of water with this code. However, I think I'm making a math error because it's not giving the correct result. I need to calculate the benefits for each user and show the maximum and how many units of water should go to each user as a result. How can I do it?
clc;
clear;
close all;
A=[6 5 7;12 14 30;35 40 42;75 55 50;85 65 60;91 70 70;96 75 72;100 80 75]; %the matrix of benefits for each user
%for 3 users
for i=1:8
v(i)=A(i,3)
%for 2 users
for j=1:8
v(j)= A(j,2);
%for 1 user
for k=1:8
v(k)=A(k,1);
end
end
end
댓글 수: 0
채택된 답변
Torsten
2022년 11월 27일
편집: Torsten
2022년 11월 27일
Not the most efficient solution, but maybe best to understand what's happening.
A=[0 0 0 ;6 5 7;12 14 30;35 40 42;75 55 50;85 65 60;91 70 70;96 75 72;100 80 75];
max_benefit = -Inf;
index_user = zeros(1,3);
units_of_water = 8;
for i = 0:units_of_water
for j = 0:units_of_water
for k = 0:units_of_water
if i+j+k <= units_of_water
benefit = A(i+1,1) + A(j+1,2) + A(k+1,3);
if benefit > max_benefit
units_of_water_per_user = [i, j, k];
max_benefit = benefit;
end
end
end
end
end
max_benefit
units_of_water_per_user
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!