我想知道是否有一种方法可以循环遍历多个不同大小的数组并从每个数组的开头修剪数据,以便在每个数组中实现相同数量的元素?
例如,如果我有:
A = [4 3 9 8 13]
B = [15 2 6 11 1 12 8 9 10 13 4]
C = [2 3 11 12 10 9 15 4 14]
我希望B和C在开头丢失一些元素,这样它们最终会成为5个元素,就像A一样,实现:
A = [4 3 9 8 13]
B = [8 9 10 13 4]
C = [10 9 15 4 14]
我该怎么做?
EDIT / UPDATE:
我接受了@excaza提出的答案,他写了一个名为“naivetrim”的好函数。我将该函数保存为.m脚本然后使用它:首先我定义了我的三个数组,正如@excaza建议的那样,调用函数:
[A, B, C] = naivetrim(A, B, C);
另一个适用于我的解决方案变体 - 基于@ Sardar_Usama的答案(循环播放)。我也喜欢这个,因为它更直接(我的水平,我可以跟踪代码中发生的事情)
A = [4 3 9 8 13]
B = [15 2 6 11 1 12 8 9 10 13 4]
C = [2 3 11 12 10 9 15 4 14]
arrays = {A,B,C}
temp = min([numel(A),numel(B), numel(C)]); %finding the minimum number of elements
% Storing only required elements
for i = 1:size(arrays,2)
currentarray = arrays{i}
arrays(i) = {currentarray(end-temp+1:end)}
end
答案 0 :(得分:3)
一个天真的循环解决方案:
function testcode()
% Sample data arrays
A = [4, 3, 9, 8, 13];
B = [15, 2, 6, 11, 1, 12, 8, 9, 10, 13, 4];
C = [2, 3, 11, 12, 10, 9, 15, 4, 14];
[A, B, C] = naivetrim(A, B, C);
end
function varargout = naivetrim(varargin)
% Assumes all inputs are vectors
% Find minumum length
lengths = zeros(1, length(varargin), 'uint32'); % Preallocate
for ii = 1:length(varargin)
lengths(ii) = length(varargin{ii});
end
% Loop through input arrays and trim any that are longer than the shortest
% input vector
minlength = min(lengths);
varargout = cell(size(varargin)); % Preallocate
for ii = 1:length(varargout)
if length(varargin{ii}) >= minlength
varargout{ii} = varargin{ii}(end-minlength+1:end);
end
end
end
返回:
A =
4 3 9 8 13
B =
8 9 10 13 4
C =
10 9 15 4 14
如果您拥有大量阵列,那么使用其他中间存储数据类型(例如cells或structures)可能会更好,分配和迭代会更“简单”。
可以在this Gist中找到几种不同类似方法的时间码。
Performance Profile, MATLAB (R2016b)
Number of Elements in A: 999999
Number of Elements in B: 424242
Number of Elements in C: 101325
Trimming, deletion: 0.012537 s
Trimming, copying: 0.000430 s
Trimming, cellfun copying: 0.000493 s
答案 1 :(得分:2)
如果矩阵不多,则可以按以下方式完成:
temp = min([numel(A),numel(B), numel(C)]); %finding the minimum number of elements
% Storing only required elements
A = A(end-temp+1:end);
B = B(end-temp+1:end);
C = C(end-temp+1:end);