How to create the "for" loop?

3 ビュー (過去 30 日間)
Rahul Verma
Rahul Verma 2023 年 4 月 10 日
コメント済み: Dyuman Joshi 2023 年 4 月 10 日
I am trying to create 'for' loop for one easy problem. It is a simple subsraction.
Let me explain more about. So i want to calculate "v" by using this formula; v = datainput - XSS
Here, the size of datainput is 34*36 and size of XSS is 34*1296.
Now, the trick is that when the substraction takes place, it should be in a manner that 1st column of datainput - /minus whole XSS, (which will give a matrix of size 34*1296). Likewise for whole 36 columns the substraction should happen. And the final result should be stored in v (of size 34*36*1296).
For this i am attaching the datainput and XSS excel files.

回答 (1 件)

Dyuman Joshi
Dyuman Joshi 2023 年 4 月 10 日
編集済み: Dyuman Joshi 2023 年 4 月 10 日
Loop approach
datainput=rand(34,36);
XSS=rand(34,1296);
%Preallocation
v=zeros(34,36,1296);
for k=1:size(datainput,2)
v(:,k,:)=datainput(:,k)-XSS;
end
Vectorized approach -
V=datainput-permute(XSS,[1 3 2]);
%Ideally one should you tolerance to compare floating point numbers
isequal(v,V)
ans = logical
1
  2 件のコメント
Rahul Verma
Rahul Verma 2023 年 4 月 10 日
In both appraoches, its showinng error. Size of matrix is not matching.
Dyuman Joshi
Dyuman Joshi 2023 年 4 月 10 日
It's working fine here. How are you importing your data?
XSS=readmatrix('XSS.xlsx');
size(XSS)
ans = 1×2
34 1296
datainput=readmatrix('datainput.xlsx');
size(datainput)
ans = 1×2
34 36
v=zeros(34,36,1296);
for k=1:size(datainput,2)
v(:,k,:)=datainput(:,k)-XSS;
end
V=datainput-permute(XSS,[1 3 2]);
isequal(v,V)
ans = logical
1

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by