

FlashChat  Actuarial Discussion  Preliminary Exams  CAS/SOA Exams  Cyberchat  Around the World  Suggestions 
DW Simpson 
Actuarial Salary Surveys 
Actuarial Meeting Schedule 
Contact DW Simpson 

Thread Tools  Search this Thread  Display Modes 
#1




matlab question
I'm pretty new to matlab and I'm trying to figure out how to do this:
b=zeros(5,10) 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 a=(1;3;1;4;4); For each row in b, I want to put a 1 in the column indexed by a, i.e.: 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 edit: I've gotten it to work with a for loop, but this seems like it shouldn't be necessary. Last edited by CuriousGeorge; 07012018 at 05:05 PM.. 
#2




Quote:

#4




Quote:
I think this is the looping code that did what I wanted: for i=1:m b(i,a(i))=1; end It worked, but it just seemed very inelegant, and I thought there must be a better way. 
#5




Solve with Linear Indexing
The Matlab matrix can also be iterated into via linearly so, in your example example, the point b(2,3) is equivalent to b(12).
So, you need to figure out which row you're on and which column you're in and calculate that linear order point. Because Matlab goes columnbycolumn for this linearly, the math problem you've got to solve is row + columnlength * column minus 1. So, your five points are the same as.. b(1,1) = b(1 + 0*5). b(2,3) = b(2 + 2*5) b(3,1) = b(3 + 0*5) b(4,4) = b(4 + 3*5) b(5,4) = b(5 + 3*5) To turn this into MATLAB script you would write: a = (1;3;1;4;4); % Your original lookup matrix. a_mod = (1:5)' + (a1) .* 5; % Converted based on columns of length 5 b(a_mod) = 1; % set each point equal to 1. If you wanted to make this a bit more generic you could change it to: a_mod = (1:size(a,1))' + (a1).*size(b,1); That would allow you to use a = [1;4;2;4] to edit the first 4 rows of b with a without throwing an error, but this'll only work if a is shorter than b. 
Thread Tools  Search this Thread 
Display Modes  

