vec2mat w/列数不同 [英] vec2mat w/ different number of columns

查看:83
本文介绍了vec2mat w/列数不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请参阅在不同的开始/结尾下按行重塑元素编号 @Divakar提供了一个很好的解决方案,但是如果列数不总是相同怎么办?

Referring to Reshape row wise w/ different starting/ending elements number @Divakar came with a nice solution but, what if the number of columns is not always the same?

样品运行-

>> 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不允许将矢量作为列号.

I took only the first 4 terms of A and put them in out, then fill the rest 2 empty cell with 0's. So the ncols = [4 6 6]. Unfortunately vet2mat doesn't allow vector as columns number.

有什么建议吗?

推荐答案

您可以雇用 bsxfun 的屏蔽功能在这里-

You can employ bsxfun's masking capability here -

%// 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

这篇关于vec2mat w/列数不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆