필터 지우기
필터 지우기

compare and sort element in two arrays in matlab?

조회 수: 13 (최근 30일)
Putri Basenda Tarigan
Putri Basenda Tarigan 2020년 11월 19일
편집: Nora Khaled 2020년 11월 19일
Hello everyone,
I have two array
a=[3 1 2]
b=[2 3 1]
each element in each array has one value, that is c. for example c(a(1))=5, c(a(2))=6, c(b(1))=9 ,..
I want to compare the c value of the same number in array a and b.
So it's like I want to compare c(a(1)) to c(b(2)) ; c(a(2)) to c(b(3)); c(a(3)) to c(b(1)). then the maximum c values will be stored in a new array (array d) in ascending order.
after that make a new array 1x3 which indicate the corresponding number of the value in array d.
How to do this in matlab?
Thanks in advance.
  댓글 수: 2
KALYAN ACHARJYA
KALYAN ACHARJYA 2020년 11월 19일
편집: KALYAN ACHARJYA 2020년 11월 19일
Sorry I don't get this question, c(a(1))=5, c(a(2))=6, c(b(1))=9 these values??
Putri Basenda Tarigan
Putri Basenda Tarigan 2020년 11월 19일
I mean there is one value of each element in each array, that is c. for example: c(a)=[5 6 4] ; c(b)=[9 3 2]

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

답변 (2개)

Ananthi Jegan
Ananthi Jegan 2020년 11월 19일
I hope that the below lines of MATLAB code would help in arriving at the above requested solution.
% As per the above description, assuming unique values in arrays “a” and “b”
a = [3 1 2 6 4 5];
b = [2 3 1 5 6 4];
% "c" is assumed to have the same values in "a" and "b”
c = [1:6];
% Initialising the arrays “da” and “db” to store the indices from “a” and “b”
da = zeros(size(c));
db = zeros(size(c));
% Find the indices of values matching in “c” with “a” and “b”
for i = 1:numel(c)
da(i) = find(a==c(i));
db(i) = find(b==c(i));
end
% Find the max values from above arrays and store in “d_actual”
d_actual = max(da,db);
% Store the sorted values of “d_actual” in “d_sorted”
d_sorted = sort(d_actual);
% New array to find the corresponding value from “d_sorted”
new_array = d_actual(d_sorted);

Nora Khaled
Nora Khaled 2020년 11월 19일
편집: Nora Khaled 2020년 11월 19일
Try this code... I hope I understood the problem correctly
clc;
clear all;
%function
c = @(x) x.^2;
%data
a=[3 1 2];
b=[2 3 1];
%merge data
md=[a;b];
mc=[c(a);c(b)];
% get postions of max values
[ind]=find(mc==max(mc));
% store max valus in d
d=mc(ind);
% get the corresponding values from a and b
cd=md(ind);
% sort d
[d,i]=sort(d);
% sort corresponding values from a and b using d
cd= cd(i);
% results:
disp('max of c in ascending order');
disp(d);
disp('corresponding data in ascending order');
disp(cd);

카테고리

Help CenterFile Exchange에서 Data Type Conversion에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by