问题描述
A = [a 2 5 8;
b 4 8 NaN]
其中a
和b
是1x3
行向量.
我需要使用以下内容获取单元格数组B
:
I need to get a cell array B
with:
B{1}=2 a
B{2}=5 a
B{3}=8 a b
B{4}=4 b
顺序无关紧要.
所以我需要相对于那些1x3
行向量a
和b
逐个元素地放置第4,5,6..th列,而不必考虑NaN
.
So I need to put the 4,5,6..th columns element by element with respect to those 1x3
row vectors a
and b
, disregarding NaN
.
我的第一次尝试是unique(A)
,但仅此一项并不能消除NaN
,也无法正确匹配.
My first try was unique(A)
, but this alone couldn't eliminate NaN
, nor can it match correctly.
也许我还需要获取每个元素(2、5、8、4、8,)排"的索引矩阵,但是我找不到方法.
Perhaps I also need to get the index matrix of at which "row" each element (2,5,8,4,8,), but I couldn't find how.
然后我尝试使用for
和if
.但是我的电脑无法处理如此大的文件.
I then tried using for
and if
. But my PC was unable to process this with huge file size.
推荐答案
所以您有一个矩阵A
:
A = [a 2 5 8;
b 4 8 NaN];
我首先将矩阵分为a
和b
以及其余部分:
I'll first split the matrix into parts consisting of a
and b
and the rest:
a_and_b = A(:,1:3);
Arest = A(:,4:end);
然后,我们将看到此Arest
矩阵中的唯一项,并删除NaN
s:
then we'll see what the unique items are in this Arest
matrix, and remove the NaN
s:
Arest_uniq = unique(Arest);
Arest_uniq = Arest_uniq(~isnan(Arest_uniq));
检查Arest
行中Arest_uniq
中元素的出现情况:
check the occurences of the elements in Arest_uniq
in rows of Arest
:
occur_A = arrayfun(@(ii) ismember(Arest_uniq,Arest(ii,:)),1:size(A,1),'uni',false);
由于基于if构造添加a
和/或b
行不是线性操作,因此我宁愿循环执行.
Because adding those rows a
and/or b
based on an if-construction isn't a linear operation, I'd rather just do it in a loop.
output = num2cell(Arest_uniq);
for ii=1:numel(output)
for jj=1:size(A,1)
if occur_A{jj}(ii)
output{ii} = [output{ii} a_and_b(jj,:)];
end
end
end
请通过步骤进行操作,分步调试,在途中检查变量,最终您将了解所有操作.因此,下次您可以亲自解决问题.
Go through this with step-by-step debugging, inspect variables on the way, and eventually you'll understand what everything does. So next time you can solve your problems yourself on the spot.
这篇关于通过Matlab重新排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!