2

我正在从 .txt 文件中读取 5 列到 5 个向量。

有时有些向量比其他向量大一个元素,所以我需要检查它们是否都等长,如果不是,我必须找出哪些是最大的并删除它们的最后一个元素。我想我应该能够在没有循环的情况下做到这一点。我最初考虑find与 with 结合使用,isequalisequal只返回一个逻辑,并且不提供有关哪些向量最大的任何信息。

[Seconds,Sensor1VStatic,Sensor2VPulsed,TemperatureC,RelativeHumidity] = importfile(path);

然后根据哪个向量长一个元素,我会做,例如

Seconds(end) = [];
Sensor1VStatic(end) = [];

如果 Seconds 和 Sensor1VStatic 比其他向量长一个元素

4

1 回答 1

3

Assume your vectors are in a cell array A:

A = {[1 2 3], [1 2 3 4], [1 2 3 4 5]};

You can get the size of each vector with

sz = cellfun(@(x)size(x,2), A);

Which will return (for the above example)

sz = [ 3 4 5]

Now you can find the shortest vector:

minLength = min(sz);

And finally, make all vectors this length:

B = cell2mat(cellfun(@(x)x(1:minLength), A, 'uniformoutput', false))';

There may be more elegant ways (and note that cellfun really is doing "implicit looping")

Applying this to your (now expanded) example, you could probably assign the output of importfile directly to the cell array - or you can do it as a separate line:

A = {Seconds,Sensor1VStatic,Sensor2VPulsed,TemperatureC,RelativeHumidity};

But it all becomes a lot of work. Instead you could do:

minLength = min(size(Seconds,1), size(Sensor1VStatic,1), size(Sensor2VPulsed,1), ...

Seconds = Seconds(1:minLength);
...

There is scope for some cleverness but it won't make things more readable, and it won't save time in the long run...

于 2013-08-28T18:50:55.860 回答