How can I automatically scale each of the elements of a Vector V to the respective size of the cell of the struct S?

조회 수: 1 (최근 30일)
I have a struct called Observations.t0 which has 140 cells -> Observations(1).t0 up to Observations(140).to and every Observation has a different amount of elements.
I want to create a Vector with ones with the length of the cell for every cell and multiply it with a value from another struct. I tried it this way:
Ratings=vertcat(ones(length(Observations(:).t0),1)*values.b(:,4));
If Observations(1).t0 had 5 elements in its cell, I want to create a vector that looks like this (1;1;1;1;1) and afterwards multiply the entire vector with the value of values.b(1,4)) which could be 3. The result would be the vector (3;3;3;3;3). Afterwards I want to do that process again with the second cell and extend my vector with the results. That could look like this: (3;3;3;3;4;4).
I get an error with the length(Observations(:).t0),1) it says to many input arguments. Can I solve that with a for loop?

채택된 답변

Wilson A N
Wilson A N 2017년 1월 18일
You can use for loop to do this as shown in the code below:
clear;
clc;
structSize = 20;
observations(structSize).t0 = [];
for i = 1:structSize
observations(i).t0 = ones(1,i);
end
values.b = rand(20,20);
Ratings = [];
for i = 1:4
Ratings = [Ratings;ones(length(observations(i).t0),1)*values.b(i,4)];
end
  댓글 수: 1
Stephen23
Stephen23 2017년 1월 18일
편집: Stephen23 2017년 1월 18일
Note that expanding the array Ratings on each loop iteration is not efficient and will show an mlint warning:
To write efficient code it is important to preallocate the array before the loop:

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Stephen23
Stephen23 2017년 1월 18일
편집: Stephen23 2017년 1월 18일
You can use arrayfun to do this quite neatly:
>> vec = [1,9,4,0];
>> obs(1).t0 = 0:4;
>> obs(2).t0 = 5;
>> obs(3).t0 = 6:7;
>> obs(4).t0 = 8:9;
>> C = arrayfun(@(s,n)n*ones(size(s.t0)),obs,vec,'uni',0);
>> out = horzcat(C{:})
out =
1 1 1 1 1 9 4 4 0 0

카테고리

Help CenterFile Exchange에서 Entering Commands에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by