简体   繁体   English

Matlab:使用逻辑索引重复输入相同的向量到矩阵

[英]Matlab: enter same vector repeatedly to matrix using logical indexing

I would like to enter the same vector of numbers repeatedly to an existing matrix at specific (row) logical indices. 我想在特定的(行)逻辑索引处向现有矩阵重复输入相同的数字向量。 This is like an extension of entering just a single number at all logical index positions (at least in my head). 这就像在所有逻辑索引位置(至少在我的头上)仅输入一个数字的扩展。

Ie, it is possible to have 即,可能有

mat    = zeros(5,3);
rowInd = logical([0 1 0 0 1]); %normally obtained from previous operation

mat(rowInd,1) = 15; 
mat =

     0     0     0
    15     0     0
     0     0     0
     0     0     0
    15     0     0

But I would like to do sth like this 但我想这样

mat(rowInd,:) = [15 6 3]; %rows 2 and 5 should be filled with these numbers

and get an assignment mismatch error. 并得到分配不匹配错误。

I want to avoid for loops for the rows or assigning vector elements single file. 我想避免行的循环或将向量元素分配给单个文件。 I have the strong feeling there is an elementary matlab operation that should be able to do this? 我有一种很强烈的感觉,应该可以执行基本的matlab运算? Thanks! 谢谢!

The problem is that your indexing picks two rows from the matrix and tries to assign a single row to them. 问题是您的索引从矩阵中选择了两行,并尝试为其分配一行。 You have to replicate the targeted row to fit your indexing: 您必须复制目标行以适合您的索引:

mat = zeros(5,3);
rowInd = logical([0 1 0 0 1]);
mat(rowInd,:) = repmat([15 6 3],sum(rowInd),1)

This returns: 返回:

mat =

     0     0     0
    15     6     3
     0     0     0
     0     0     0
    15     6     3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM