Problem with answer in my code

조회 수: 5 (최근 30일)
Anastasiia Hanchevska
Anastasiia Hanchevska 2023년 3월 15일
답변: Elijah Gendron 2023년 3월 16일
I have this code below, and it should give answer like this at the top of the screenshot, but it giving this another answer, idk what problem. I need code where i will get 5 vectors(cause i have 5 index in matrix) and every vector should have one max value, for example if we will take first vector it will have the max number from first index and the min number in each subsequent index, second vector will have max number from second index and min number in all others vectors. Hope you will understand
X = [2 5; 3 6; 1 7; 3 6; 1 5];
[m, n] = size(X);
for i = 1:n
temp = X(:, i);
for j = 1:m
if X(j, i) == max(temp)
temp(j) = min(temp);
elseif X(j, i) == min(temp)
temp(j) = max(temp);
end
end
eval(sprintf('X%d = temp'';', i));
end
% show results
for i = 1:n
eval(sprintf('disp([''X%d = '', mat2str(X%d)]);', i, i));
end
X1 = [2 1 3 1 3] X2 = [7 6 5 6 7]

답변 (1개)

Elijah Gendron
Elijah Gendron 2023년 3월 16일
Would be easier to do something along these lines:
This will give you the matrix that you can then strip into indvidual rows if you want
XA = [2 3 1 3 1]; % Set the variables that will make the 'base' matrix
XB = [5 6 7 6 5]; % Set the diagonal values
n = length(XA);
A = repmat(XA,n,1); % Generate the base matrix
B = XB.*eye(n); % Generate diagonals
ix = find(B); % Get indicies of non zero values
A(ix) = B(ix); % Replace diagonal values in A matrix
disp(A)
5 3 1 3 1 2 6 1 3 1 2 3 7 3 1 2 3 1 6 1 2 3 1 3 5

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by