How to add zeros to 2 x vectors where there are no matches, to get the same length ?

2 次查看(过去 30 天)
x=[1 2 3 4];
y=[1 2 3 1];
x1=[3 4 5 6 7 8];
y1=[2 6 4 2 5 3];
[x, y, x1, y1] = Tout_Ajuster(x, y, x1, y1)
I want to put zeros where there is no match in x axes to get the same length for (x and x1) so I write a small code (Tout_Ajuster.m) in the output, x1 misses (5 and 6) so y1 miss(4 and 2) What is missing in my function < Tout_Ajuster.m > ???
  2 个评论
Jon
Jon 2015-7-29
It would help if you gave us the expected outputs for x1 and y1. Otherwise it's not clear what you're trying to do.
Joel Sande
Joel Sande 2015-7-29
% This is the expected output
x = [1 2 3 4 0 0 0 0]
x1 = [0 0 3 4 5 6 7 8]
y = [1 2 3 1 0 0 0 0]
y1 = [0 0 2 6 4 2 5 3]
%% Jon is very close to the answer, %% this is an other example :
ax = [3 5 9];
ay = [1 5 6];
bx = [1 2 10 15];
by = [3 4 5 2];
from that I want :
ax = [0 0 3 5 9 0 0];
ay = [0 0 1 5 6 0 0];
bx = [1 2 0 0 0 10 15];
by = [3 4 0 0 0 5 2];

请先登录,再进行评论。

采纳的回答

Joel Sande
Joel Sande 2015-7-29
In this example, Test_Ajuster.m is calling Tout_Ajuster.m

更多回答(3 个)

Jon
Jon 2015-7-29
Your question seems ambiguous to me, but based off my interpretation, see if this code gives you the result you're looking for:
% This assumes that none of the matching x values are 0
N = max(numel(x),numel(x1));
xout = zeros(1,N);
yout = zeros(1,N);
x1out = zeros(1,N);
y1out = zeros(1,N);
% Reinsert the known values of x and y
xout(1:numel(x)) = x;
yout(1:numel(y)) = y;
% Values in x1 (and the correponding y1 positions) that do not appear in x are set to zero
for i = 1:numel(x)
matching = find(x(i) == x1);
if isempty(matching) == 1
continue
else
x1out(matching) = x1(matching);
y1out(matching) = y1(matching);
end
end
Gives the following results:
xout =
1 2 3 4 0 0
yout =
1 2 3 1 0 0
x1out =
3 4 0 0 0 0
y1out =
2 6 0 0 0 0

Azzi Abdelmalek
Azzi Abdelmalek 2015-7-29
n=max(numel(x),numel(x1))
x=[x zeros(1,n)]
x1=[x1 zeros(1,n)]
y=[y zeros(1,n)]
y1=[y1 zeros(1,n)]

Joel Sande
Joel Sande 2015-7-29
%% It is working now. Thank
ax = [3 5 9];
ay = [1 5 6];
bx = [1 2 10 15];
by = [3 4 5 2];
>> [a, b, c, d] = Tout_Ajuster(ax,ay,bx,by)
a =
0 0 3 5 9 0 0
b =
0 0 1 5 6 0 0
c =
1 2 0 0 0 10 15
d =
3 4 0 0 0 5 2

类别

Help CenterFile Exchange 中查找有关 Startup and Shutdown 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by