필터 지우기
필터 지우기

How to write a matlab code for a given algorithm from a given array and function?

조회 수: 7 (최근 30일)
HAT
HAT 2021년 12월 9일
댓글: Walter Roberson 2021년 12월 10일
I would like to write a matlab code to calculate the value of a function of two variables g(i,j) = i + j + 1 for every pair (i,j) in the set MV = {[1,3]; [2,4]; [5,6]; [5,4]; [7,2]} so that the output results in g = {5, 7, 12, 10, 9} based on the following algorithm:
Step 0. MV_0 = empty set;
Step 1. h=1;
Step 2. while MV_h ~= empty set {
Step 3. for every (i,j) in MV {
Step 4. g(i,j)
Step 5. }
Step 6. h=h++
Step 7. }
So far I have tried the following, but I couldn't figure it out. Please any hint/assistance. Thanks in advance!
MV = {}; % Step 0
h = 1; % Step 1
% MV= intersect(r(r==1),s(s==3))
while isempty(MV{h})==0 % MV{h} is nonempty from Step 2
MV = {[1,3]; [2,4]; [5,6]; [5,4]; [7,2]};
% Step 3, for every (i,j) in EMV{h}
for i=1:length(MV)
for j = 1:length(MV)
MV{h} = g(i,j); % Step 4
end
end
h = h+1; % Step 6
end
Index exceeds the number of array elements. Index must not exceed 0.
g % to get the final result g = {5, 7, 12, 10, 9}
% subfunction
function y = g(i,j)
y = i+j+1;
end

답변 (1개)

Walter Roberson
Walter Roberson 2021년 12월 9일
MATLAB does not permit using () to create pairs.
MATLAB does not have a "tuple" datatype. The closest equivalent for it are vectors (for homogenous numeric data types) or cell array vectors (for mixed data)
MV = {[1,3], [2,4], [5,6], [5,4], [7,2]}
  댓글 수: 2
HAT
HAT 2021년 12월 9일
편집: HAT 2021년 12월 9일
@Walter Roberson I've edited now. But it has still an error.
Walter Roberson
Walter Roberson 2021년 12월 10일
MV = {}; % Step 0
h = 1; % Step 1
% MV= intersect(r(r==1),s(s==3))
while isempty(MV{h})==0 % MV{h} is nonempty from Step 2
MV = {[1,3]; [2,4]; [5,6]; [5,4]; [7,2]};
% Step 3, for every (i,j) in EMV{h}
for i=1:length(MV)
for j = 1:length(MV)
MV{h} = g(i,j); % Step 4
end
end
h = h+1; % Step 6
end
Index exceeds the number of array elements. Index must not exceed 0.
g % to get the final result g = {5, 7, 12, 10, 9}
% subfunction
function y = g(i,j)
y = i+j+1;
end
This makes sense. You start out MV as empty, {}, so MV{1} does not exist and so you cannot isempty() it.
Step 0. MV_0 = empty set;
Step 1. h=1;
Step 2. while MV_h ~= empty set {
Step 3. for every (i,j) in MV {
Step 4. g(i,j)
Step 5. }
Step 6. h=h++
Step 7. }
MV_h is not the same as MV_0, and you have not defined MV_h . If MV_h is intended to represent MV indexed at h then you have the problem that MV indexed at 1 has not been defined since you initialized MV at 0.

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

카테고리

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