gpt4 book ai didi

matlab - 具有/不同列数的 vec2mat

转载 作者:行者123 更新时间:2023-12-04 23:22:39 25 4
gpt4 key购买 nike

引用Reshape row wise w/ different starting/ending elements number @Divakar 提供了一个很好的解决方案,但是,如果列数不总是相同怎么办?

样本运行 -

>> A'
ans =
4 9 8 9 6 1 8 9 7 7 7 4 6 2 7 1
>> out
out =
4 9 8 9 0 0
6 1 8 9 7 7
7 4 6 2 7 1

我只取了 A 的前 4 项并将它们放入,然后用 0 填充其余 2 个空单元格。所以 ncols = [4 6 6]。不幸的是 vet2mat 不允许向量作为列号。

有什么建议吗?

最佳答案

您可以雇用 bsxfun此处的屏蔽功能 -

%// Random inputs
A = randi(9,1,15)
ncols = [4 6 5]

%// Initialize output arary of transposed size as compared to the desired
%// output arary size, as we need to insert values into it row-wise and MATLAB
%// follows column-major indexing
out = zeros(max(ncols),numel(ncols));

mask = bsxfun(@le,[1:max(ncols)]',ncols); %//'# valid positions mask for output
out(mask) = A; %// insert input array elements
out = out.' %//'# transpose output back to the desired output array size

代码运行-

A =
5 3 7 2 7 2 4 6 8 1 9 7 5 4 5
ncols =
4 6 5
out =
5 3 7 2 0 0
7 2 4 6 8 1
9 7 5 4 5 0

关于matlab - 具有/不同列数的 vec2mat,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28026844/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com